Weiter | Weiter | Weiter | Weiter | Kommentar

all-inOne, section 7.

7.  Exceptions

See also: http://java.sun.com/docs/books/jls/html/11.doc.html#44044 and http://www.cs.rit.edu/usr/local/jdk/docs/api/java.lang/Exception.html

When a Java program violates the semantic constraints of the Java language, a Java Virtual Machine signals this error to the program as an exception. An example of such a violation is an attempt to index outside the bounds of an array.

Java specifies that an exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer. An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.

Java programs can also throw exceptions explicitly, using throw statement.

The Java language checks, at compile time, that a Java program contains handlers for checked exceptions, by analyzing which checked exceptions can result from execution of a method or constructor.

7.1.  Runtime Exceptions are Not Checked

The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of Java, having to declare such exceptions would not aid significantly in establishing the correctness of Java programs. Many of the operations and constructs of the Java language can result in runtime exceptions. The information available to a Java compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such runtime exceptions cannot occur, even though this may be obvious to the Java programmer. Requiring such exception classes to be declared would simply be an irritation to Java programmers.

For example, certain code might implement a circular data structure that, by construction, can never involve null references; the programmer can then be certain that a NullPointerException cannot occur, but it would be difficult for a compiler to prove it. The theorem-proving technology that is needed to establish such global properties of data structures is beyond the scope of this Java Language Specification.

7.2.  Try

When an exception is thrown, control is transferred from the code that caused the exception to the nearest dynamically-enclosing catch clause of a try statement that handles the exception.

Syntax:

try
{
    statement sequence
}

The exception can be thrown and caught in the same try block if necessary.

try
{
    f();
}
catch (Exception e)	{
	throw e;
}

7.3.  Catch

It can be followed by zero or more catch blocks:

catch ( parameter )
{
    statement sequence
}

Example:

try {
    anObject.f();
    anObject.g();
} catch (SomeExeption_1 e) {
    // do something to recover
}
catch (SomeExeption_2 e) {
    // do something to recover
}

7.4.  Finally

The finally block will be always executed, regardless of what happens in the try block.

This provides a place where you can put statements which will be always executed.

finally ( )
{
    statement sequence
}

7.5.  Throw

A throw statement allows an exception to be thrown.

Syntax:

throw typeThrowableException;

Example:

throw new Exception("Nop, this was not too good!");

7.6.  Exceptions are Precise

Exceptions in Java are precise: when the transfer of control takes place, all effects of the statements executed and expressions evaluated before the point from which the exception is thrown must appear to have taken place. No expressions, statements, or parts thereof that occur after the point from which the exception is thrown may appear to have been evaluated. If optimized code has speculatively executed some of the expressions or statements which follow the point at which the exception occurs, such code must be prepared to hide this speculative execution from the user-visible state of the Java program.

7.7.  Example 1

Src/7/Excep_1.java.minusSTART_STOP


 1      /**
 2       * This class plays with exceptions
 3       *
 4       * @version   $Id$
 5       *
 6       * @author    hp bischof
 7       *
 8       * Revisions:
 9       *      $Log$
10       */
11      
12      public class Excep_1 {
13      
14        private int convert(String s) {
15              int result = 0;
16      
17              try {
18                      result = Integer.parseInt(s);
19              } catch ( NumberFormatException e ) {
20                      System.out.println("Haeh? " + e );
21                      e.printStackTrace();
22              }
23              return result;
24        }
25      
26        public static void main(String[] args) {
27              new Excep_1().convert("42");
28              new Excep_1().convert("opa");
29        }
30      }

Source Code: Src/7/Excep_1.java

Result:

% java Excep_1
Haeh? java/lang/NumberFormatException: opa
java/lang/NumberFormatException: opa
        at java/lang/Integer.parseInt(Integer.java)
        at java/lang/Integer.parseInt(Integer.java)
        at Excep_1.convert(Excep_1.java:18)
        at Excep_1.main(Excep_1.java:28)

7.8.  Example 2

Src/7/Excep_2.java.minusSTART_STOP


 1      /**
 2       * This class plays with exceptions
 3       *
 4       * @version   $Id$
 5       *
 6       * @author    hp bischof
 7       *
 8       * Revisions:
 9       *      $Log$
10       */
11      
12      public class Excep_2 {
13      
14        private void f(int n) throws NullPointerException,
15                                     InterruptedException {
16              System.out.println("f(" + n + ")" );
17              switch (n)      {
18                      case 1:  throw new NullPointerException("1");
19                      default: throw new InterruptedException("default");
20              }
21        }
22      
23        public static void main(String[] args) {
24              for (int index = 1; index < 3; index ++ )       {
25                      try {
26                              new Excep_2().f(index);
27                      } catch (NullPointerException e)        {
28                              e.printStackTrace();
29                      }
30                      
31                      catch (Exception e)     {
32                              System.out.println(e.getMessage() );
33                      }
34                      
35              }
36        }
37      }

Source Code: Src/7/Excep_2.java

Result:

% java Excep_2
f(1)
java/lang/NullPointerException: 1
        at Excep_2.f(Excep_2.java:17)
        at Excep_2.main(Excep_2.java:25)
f(2)
default

Typical compiler errors:

Exception java/lang/Exception must be caught,
or it must be declared in the throws clause of this method.
                        new Excep_2().f(3);
                                       ^
1 error

7.9.  Try Example

Src/7/Try.java.minusSTART_STOP


 1      /**
 2       * This class plays with exceptions
 3       *
 4       * @version   $Id$
 5       *
 6       * @author    hp bischof
 7       *
 8       * Revisions:
 9       *      $Log$
10       */
11      
12      public class Try {
13      
14        private void f(int n) throws Exception {
15              System.out.println("f(" + n + ")" );
16              switch (n)      {
17                      case 1:  throw new NullPointerException("1");
18                      default: throw new Exception("default");
19              }
20        }
21      
22        public static void main(String[] args) {
23              int countExceptions = 0;
24              for (int index = 0; index < 3; index ++ )       {
25                      try {
26                              new Try().f(index);
27                      } catch (Exception e)   {
28                              e.printStackTrace();
29                      }
30                      
31                      finally  {
32                              countExceptions ++;
33                      }
34              }
35              System.out.println("Caught " + countExceptions +
36                                  " exceptions.");
37        }
38      }

Source Code: Src/7/Try.java

Result:

% java Try
f(0)
java/lang/Exception: default
        at Try.f(Try.java:18)
        at Try.main(Try.java:26)
f(1)
java/lang/NullPointerException: 1
        at Try.f(Try.java:17)
        at Try.main(Try.java:26)
f(2)
java/lang/Exception: default
        at Try.f(Try.java:18)
        at Try.main(Try.java:26)
Caught 3 exceptions.

7.10.  Example Throw and Re-throw

Src/7/Deep.java.minusSTART_STOP


 1      /**
 2       * This class plays with exceptions
 3       *
 4       * @version   $Id$
 5       *
 6       * @author    hp bischof
 7       *
 8       * Revisions:
 9       *      $Log$
10       */
11      
12      public class Deep {
13      
14        private void f() {
15              try {
16                      throw new Exception("in f()");
17              } catch (Exception e)   {
18                      System.out.println(e.getMessage() );
19              }
20        }
21      
22        private void g(int n) throws NullPointerException,
23                                     InterruptedException {
24              System.out.println("\t++ in g(): n = " + n );
25              switch (n)      {
26                      case 1:  throw new NullPointerException("in g(): 1");
27                      default: throw new InterruptedException("in g() default");
28              }
29        }
30      
31      
32      
33      
34      
35      
36      
37        private void h() throws Exception {
38              try {
39                      g(1);
40                      g(0);
41              } catch (NullPointerException e)        {
42                      e.printStackTrace();
43                      e.fillInStackTrace();
44                      throw e;
45              }
46              catch (InterruptedException e)  {
47                      System.out.println("in h(): catch (Exception e)");
48                      System.out.println(e.getMessage() );
49                      throw e;
50              }
51              finally {
52                      System.out.println("h is done()");
53              }
54        }
55      
56        private void i() {
57              try {
58                      h();
59              } catch (Exception e)   {
60                      System.out.println("\t++ in g()!catch ");
61                      e.printStackTrace();
62              }
63        }
64      
65        public static void main(String[] args) {
66              new Deep().f();
67              new Deep().i();
68        }
69      }

Source Code: Src/7/Deep.java

Result:

% java Deep
in f()
        ++ in g(): n = 1
java/lang/NullPointerException: in g(): 1
        at Deep.g(Deep.java:25)
        at Deep.h(Deep.java:32)
        at Deep.i(Deep.java:51)
        at Deep.main(Deep.java:60)
h is done()
        ++ in g()!catch 
java/lang/NullPointerException: in g(): 1
        at Deep.h(Deep.java:36)
        at Deep.i(Deep.java:51)
        at Deep.main(Deep.java:60)

7.11.  A 'Real Example'

Use:

Src/7/TestAbstract.java.minusSTART_STOP


 1              
 2      
 3      public class TestAbstract {
 4      
 5        public static void main(String args[])
 6        {
 7              Square aSquare;
 8              Circle aCircle;
 9      
10              for (int index = 1; index >=  -1; index -= 2 ) {
11                      try {
12                              aSquare = new Square(index);
13                              aCircle = new Circle(index);
14              
15                              System.out.println( "Circle");
16                              System.out.println( "\t" +  aCircle.area() );
17                              System.out.println( "\t" +  aCircle.perimeter() );
18              
19                              System.out.println( "Square");
20                              System.out.println( "\t" +  aSquare.area() );
21                              System.out.println( "\t" +  aSquare.perimeter() );
22                      }
23                      catch ( Exception e )   {
24                              System.out.println(e.getMessage() );
25                      }
26              }
27      
28        }
29      }

Source Code: Src/7/TestAbstract.java

Src/7/Area.java.minusSTART_STOP


 1      /**
 2       * Abstract class
 3       * @version   $Id$
 4       *
 5       * @author    hp bischof
 6       *
 7       * Revisions:
 8       *      $Log$
 9       */
10      
11      abstract class Area {
12      
13        public abstract int area() throws Exception;
14        public abstract int perimeter() throws Exception;
15      
16      }
17      

Source Code: Src/7/Area.java

Src/7/Circle.java.minusSTART_STOP


 1      /**
 2       * This class implements a Circle class.
 3       *
 4       * @version   $Id$
 5       *
 6       * @author    hp bischof
 7       *
 8       * Revisions:
 9       *      $Log$
10       */
11      
12      public class Circle extends Area {
13      
14        private int radius;   
15      
16        public Circle(int _radius) throws Exception {
17              if ( radius < 0 )
18                      throw new Exception("Negativ radius (" +
19                                      radius + ") is not acceptable");
20              else
21                      radius = _radius;
22        }
23      
24        public int area() throws Exception    {
25              if ( radius < 0 )
26                      throw new Exception("Circle is not initialized");
27              else
28                      return (int)(Math.PI * radius * radius);
29        }
30      
31        public int perimeter() throws Exception {
32              if ( radius < 0 )
33                      throw new Exception("Circle is not initialized");
34              else
35                      return (int)(Math.PI * radius * radius);
36        }
37      
38      }

Source Code: Src/7/Circle.java

Src/7/Square.java.minusSTART_STOP


 1      /**
 2       * This class implements a Square class.
 3       *
 4       * @version   $Id$
 5       *
 6       * @author    hp bischof
 7       *
 8       * Revisions:
 9       *      $Log$
10       */
11      
12      public class Square extends Area {
13      
14        private int length;   
15      
16        public Square(int _length) throws Exception {
17              if ( _length < 0 )
18                      throw new Exception("Negative length (" +
19                                      length + ") is not acceptable");
20              else
21                      length = _length;
22        }
23      
24        public int area() throws Exception {
25              if ( length < 0 )
26                      throw new Exception("Square is not initialized");
27              else
28                      return length * length;
29        }
30      
31        public int perimeter() throws Exception {
32              if ( length < 0 )
33                      throw new Exception("Square is not initialized");
34              else
35                      return 4 * length;
36        }
37      
38      }

Source Code: Src/7/Square.java

7.12.  Reading From Files

Src/7/FileIO.java.minusSTART_STOP


 1      import java.io.*;
 2      public class FileIO {
 3      
 4        static void cp(String inF, String outF )      {
 5              DataInputStream in;
 6              DataOutputStream out;
 7      
 8              try {
 9                      in = new DataInputStream(
10                              new FileInputStream(inF) );
11                      out = new DataOutputStream(
12                              new FileOutputStream(outF) );
13                      try {
14                              do {
15                                      out.writeByte (in.readByte() );
16                              } while ( true );
17                      }
18                      catch ( EOFException e )        {
19                              in.close();
20                              out.close();
21                      }
22              }
23              catch ( FileNotFoundException e )       {
24                      e.printStackTrace();
25                      System.out.println("Can't find the file!");
26              }
27              catch ( IOException e ) {  // Throws: IOException !!!
28                      e.printStackTrace();
29                      System.out.println("Could not be opened for writing!");
30              }
31              catch ( Exception e )   {
32                      System.out.println("Can't find the file!");
33              }
34        }
35      
36        public static void main(String args[]) {
37              if ( args.length != 2 ) 
38                      System.out.println("Usage: java FileIO f1 f2");
39              else    {
40                      System.out.println(args[0] + "  " + args[1] );
41                      cp(args[0], args[1]);
42              }
43        }
44      }

Source Code: Src/7/FileIO.java

Result:

% java FileIO x xx
x  x
% ls -l x
-rw-------   1 hpb      fac           24 Mar 19 11:06 x
% java FileIO x xx
x  xx
% chmod 000 x
% java FileIO x xx
x  xx
java/gio.FileNotFoundException: x
        at java/gio.FileInputStream.<init>(FileInputStream.java)
        at FileIO.cp(FileIO.java:13)
        at FileIO.main(FileIO.java:45)
Can't find the file!
% chmod 644 x ; chmod 000 xx; ls -l x xx
-rw-r--r--   1 hpb      fac           24 Mar 19 11:06 x
----------   1 hpb      fac           24 Mar 19 11:08 xx
% java FileIO x xx
x  xx
java/gio.FileNotFoundException: xx
        at java/gio.FileOutputStream.<init>(FileOutputStream.java)
        at FileIO.cp(FileIO.java:15)
        at FileIO.main(FileIO.java:45)
Can't find the file!
% rm x xx
rm: xx: override protection 0 (yes/no)? y
% java FileIO x xx
x  xx
java/gio.FileNotFoundException: x
        at java/gio.FileInputStream.<init>(FileInputStream.java)
        at FileIO.cp(FileIO.java:13)
        at FileIO.main(FileIO.java:45)
Can't find the file!

7.13.  Exception Index

7.14.  Exception Class

See also http://www.cs.rit.edu/usr/local/jdk/docs/api/java.lang/Exception.html.

Exception()

Constructs an Exception with no specified detail message.

Exception(String)

Constructs an Exception with the specified detail message.

7.15.  Throwable

Exception Class is a subclass of
http://www.cs.rit.edu/usr/local/jdk/docs/api/java.lang/Throwable.html.

fillInStackTrace()
Fills in the execution stack trace.
getLocalizedMessage()
Creates a localized description of this Throwable.
getMessage()
Returns the detail message of this throwable object.
printStackTrace()
Prints this Throwable and its backtrace to the standard error stream.
printStackTrace(PrintStream)
Prints this Throwable and its backtrace to the specified print stream.
printStackTrace(PrintWriter)
Prints this Throwable and its backtrace to the specified print writer.
toString()
Returns a short description of this throwable object.

7.16.  Create a new Exception class

Use standard inheritance techniques. The superclass should be http://www.cs.rit.edu/usr/local/jdk/docs/api/java.lang/Throwable.html or a sub class.

Src/7/NumberException.java.minusSTART_STOP


 1      /**
 2       * Thrown to indicate that a method has been passed
 3       * an illegal or inappropriate ssid.
 4       */
 5      
 6      class  NumberException extends Exception
 7      {
 8              /**
 9               * Constructs an NumberException with no detail message
10               */
11              public NumberException()        {
12                      super();
13              }
14      
15              /**
16               * Constructs an NumberException with Number.Exception detail message
17               *
18               ** @param    s    the detail message.
19               */
20              public NumberException(String s)        {
21                      super(s);
22              }
23      }

Source Code: Src/7/NumberException.java


Weiter | Weiter | Weiter | Weiter | Kommentar


Created by unroff, java2html & & hp-tools. © by csfac. All Rights Reserved (2003).
It is not allowed to print these pages on a CAST printer.
Last modified 11/February/03