Weiter | Weiter | Weiter | Weiter | Kommentar

all-inOne, section 8.

8.  Exceptions and Assertions

8.1.  Exceptions

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

From: http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.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.

8.2.  Runtime Exceptions

8.3.  Compiletime Exceptions

8.4.  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.

8.5.  Runtime Exceptions--The Controversy

Copied from: http://java.sun.com/docs/books/tutorial/essential/exceptions/

8.6.  Throwable and Error

Please see: http://www.cs.rit.edu/usr/local/jdk/docs/api/index.html

Src/7/ErrorE.java.minusSTART_STOP


public class ErrorE {

  private void thisMethodThrowsAnE(int index) throws Exception, Error {
        
        if ( index == 0 )       {
                System.out.println("thisMethodThrowsAnException() ---> " );
                throw new Exception("in thisMethodThrowsAnException");
        } else {
                System.out.println("thisMethodThrowsAnError() ---> " );
                throw new Error("in thisMethodThrowsAnException");
        }

  }

  private void caller() {
        for ( int index = 0; index < 2; index ++ )      {
                try {
                        new ErrorE().thisMethodThrowsAnE(index);
                } catch (Exception e)   {
                        e.printStackTrace();
                } catch (Error e)       {
                        e.printStackTrace();
                } finally       {
                        System.out.println("Finally");
                System.out.println("Ok, a few things to clean up" );
                }
        }
  }

  public static void main(String[] args) {
        new ErrorE().caller();
  }
}

Source Code: Src/7/ErrorE.java

java ErrorE
thisMethodThrowsAnException() ---> 
java.lang.Exception: in thisMethodThrowsAnException
        at ErrorE.thisMethodThrowsAnE(ErrorE.java:7)
        at ErrorE.caller(ErrorE.java:18)
        at ErrorE.main(ErrorE.java:31)
Finally
Ok, a few things to clean up
thisMethodThrowsAnError() ---> 
java.lang.Error: in thisMethodThrowsAnException
        at ErrorE.thisMethodThrowsAnE(ErrorE.java:10)
        at ErrorE.caller(ErrorE.java:18)
        at ErrorE.main(ErrorE.java:31)
Finally
Ok, a few things to clean up

8.7.  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;
}

8.8.  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
}

8.9.  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
}

8.10.  Throw

A throw statement allows an exception to be thrown.

Syntax:

throw typeThrowableException;

Example:

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

8.11.  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.

8.12.  Handling Asynchronous Exceptions

--
An invocation of the stop() (Thread or ThreadGroup)
--
An internal error in the Java virtual machine

8.13.  Example 1

Src/7/Excep_1.java.minusSTART_STOP


/**
 * This class plays with exceptions
 *
 * @version   $Id$
 *
 * @author    hp bischof
 *
 * Revisions:
 *      $Log$
 */

public class Excep_1 {

  private int convert(String s) {
        int result = 0;

        try {
                result = Integer.parseInt(s);
        } catch ( NumberFormatException e ) {
                System.out.println("Haeh? " + e );
                e.printStackTrace();
        }
        return result;
  }

  public static void main(String[] args) {
        new Excep_1().convert("42");
        new Excep_1().convert("opa");
  }
}

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)

8.14.  Example 2

Src/7/Excep_2.java.minusSTART_STOP


/**
 * This class plays with exceptions
 *
 * @version   $Id$
 *
 * @author    hp bischof
 *
 * Revisions:
 *      $Log$
 */

public class Excep_2 {

  private void f(int n) throws NullPointerException,
                               InterruptedException {
        System.out.println("f(" + n + ")" );
        switch (n)      {
                case 1:  throw new NullPointerException("1");
                default: throw new InterruptedException("default");
        }
  }

  public static void main(String[] args) {
        for (int index = 1; index < 3; index ++ )       {
                try {
                        new Excep_2().f(index);
                } catch (NullPointerException e)        {
                        e.printStackTrace();
                }
                
                catch (Exception e)     {
                        System.out.println(e.getMessage() );
                }
                
        }
  }
}

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

-----

8.15.  Example 3

Src/7/Excep_3.java.minusSTART_STOP


public class Excep_3 {

  private void thisMethodThrowsAnException() throws Exception {
        System.out.println("thisMethodThrowsAnException() ---> " );
        throw new Exception("in thisMethodThrowsAnException");

        // javac Excep_3.java 
        // Excep_3.java:6: unreachable statement
        // System.out.println("thisMethodThrowsAnException() <--- " );
        //  ^
        // 1 error
        // System.out.println("thisMethodThrowsAnException() <--- " );
  }

  private void caller() {
        try {
                new Excep_3().thisMethodThrowsAnException();
                return;
        } catch (Exception e)   {
                e.printStackTrace();
                return;
        } finally       {
                System.out.println("Finally");
                System.out.println("Ok, a few things to clean up" );
        }
  }

  public static void main(String[] args) {
        new Excep_3().caller();
  }
}

Source Code: Src/7/Excep_3.java

Result:

% java Excep_3
thisMethodThrowsAnException() ---> 
java.lang.Exception: in thisMethodThrowsAnException
        at Excep_3.thisMethodThrowsAnException(Excep_3.java:5)
        at Excep_3.caller(Excep_3.java:18)
        at Excep_3.main(Excep_3.java:30)
Finally
Ok, a few things to clean up

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

-----

8.16.  Try Example

Src/7/Try.java.minusSTART_STOP


/**
 * This class plays with exceptions
 *
 * @version   $Id$
 *
 * @author    hp bischof
 *
 * Revisions:
 *      $Log$
 */

public class Try {

  private void f(int n) throws Exception {
        System.out.println("f(" + n + ")" );
        switch (n)      {
                case 1:  throw new NullPointerException("1");
                default: throw new Exception("default");
        }
  }

  public static void main(String[] args) {
        int countExceptions = 0;
        for (int index = 0; index < 3; index ++ )       {
                try {
                        new Try().f(index);
                } catch (Exception e)   {
                        e.printStackTrace();
                }
                
                finally  {
                        countExceptions ++;
                }
        }
        System.out.println("Caught " + countExceptions +
                            " exceptions.");
  }
}

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.

8.17.  Example Throw and Re-throw

Src/7/Deep.java.minusSTART_STOP


// What is the exceution order?

public class Deep {
  static int exceptionCounter = 0;
  static final int  MAX = 2;

  private void importantFunction(int n) throws NullPointerException,
                               InterruptedException {
        System.out.println("importantFunction -->");
        switch (n)      {
                case 1:  throw new NullPointerException("1");
                default: throw new InterruptedException("default");
        }
  }


  private void smartFunction() throws Exception {
        try {
                importantFunction(exceptionCounter);
                importantFunction(exceptionCounter);
        } catch (NullPointerException e)        {
                e.printStackTrace();
                throw new Exception("Programming error, Please call 555 1234 321");
        } catch (InterruptedException e)        {
                e.printStackTrace();
                throw new Exception("User Error error, Please call your brain");
        }
        finally {
                if ( ++exceptionCounter >= MAX )        {
                        System.err.println("Something is wrong");
                        System.err.println("BYE");
                        System.exit(1);////// never do this
                }
        }
  }

  public static void main(String[] args) {
        try {
                Deep aDeep = new Deep();
                System.out.println("----> ");
                aDeep.smartFunction();
                System.out.println("====> ");
                aDeep.smartFunction();
        } catch (Exception e)   {
                System.out.println("Main ");
                e.printStackTrace();
        }
  }
}

Source Code: Src/7/Deep.java

Result:

% java Deep
----> 
importantFunction -->
java.lang.InterruptedException: default
        at Deep.importantFunction(Deep.java:10)
        at Deep.smartFunction(Deep.java:17)
        at Deep.main(Deep.java:39)
Main 
java.lang.Exception: User Error error, Please call your brain
        at Deep.smartFunction(Deep.java:24)
        at Deep.main(Deep.java:39)

8.18.  Exceptions and Inheritance

Src/7/ExceptionsAndInheritance1.java.minusSTART_STOP


// What is the exceution order?

public class ExceptionsAndInheritance1 {

  public void importantFunction() throws InterruptedException {
        System.out.println("ExceptionsAndInheritance1:importantFunction -->");
        throw new InterruptedException("ExceptionsAndInheritance1.java");
  }

  public static void main(String[] args) {
        try {
                new ExceptionsAndInheritance1().importantFunction();
        } catch (Exception e)   {
                System.out.println("Main ");
                e.printStackTrace();
        }
  }
}

Source Code: Src/7/ExceptionsAndInheritance1.java

Src/7/ExceptionsAndInheritance2.java.minusSTART_STOP


// What is the execution order?

public class ExceptionsAndInheritance2 extends
        ExceptionsAndInheritance1 {

//  private void importantFunction() {
  public void importantFunction() {
        System.out.println("ExceptionsAndInheritance2:importantFunction -->");
  }

  public static void main(String[] args) {
        ExceptionsAndInheritance2 e2 = new ExceptionsAndInheritance2();
        ExceptionsAndInheritance1 e1 = (ExceptionsAndInheritance2)e2;
                e2.importantFunction();
        try {
                e1.importantFunction();
        } catch (Exception e)   {
                System.out.println("Main ");
                e.printStackTrace();
        }
  }
}

Source Code: Src/7/ExceptionsAndInheritance2.java

Will it compile? explain your answer.

8.19.  A 'Real Example'

Use:

Src/7/TestAbstract.java.minusSTART_STOP


            

public class TestAbstract {

  public static void main(String args[])
  {
        Square aSquare;
        Circle aCircle;

        for (int index = 1; index >=  -1; index -= 2 ) {
                try {
                        aSquare = new Square(index);
                        aCircle = new Circle(index); 
        
                        System.out.println( "Circle");
                        System.out.println( "\t" +  aCircle.area() );
                        System.out.println( "\t" +  aCircle.perimeter() );
        
                        System.out.println( "Square");
                        System.out.println( "\t" +  aSquare.area() );
                        System.out.println( "\t" +  aSquare.perimeter() );
                }
                catch ( Exception e )   {
                        System.out.println(e.getMessage() );
                }
        }

  }
}

Source Code: Src/7/TestAbstract.java

Src/7/Area.java.minusSTART_STOP


/**
 * Abstract class
 * @version   $Id$
 *
 * @author    hp bischof
 *
 * Revisions:
 *      $Log$
 */

abstract class Area {

  public abstract int area() throws Exception;
  public abstract int perimeter() throws Exception;

}


Source Code: Src/7/Area.java

Src/7/Circle.java.minusSTART_STOP


/**
 * This class implements a Circle class.
 *
 * @version   $Id$
 *
 * @author    hp bischof
 *
 * Revisions:
 *      $Log$
 */

public class Circle extends Area {

  private int radius;   

  public Circle(int _radius) throws Exception {
        if ( radius < 0 )
                throw new Exception("Negativ radius (" +
                                radius + ") is not acceptable");
        else
                radius = _radius;
  }

  public int area() throws Exception    {
        if ( radius < 0 )
                throw new Exception("Circle is not initialized");
        else
                return (int)(Math.PI * radius * radius);
  }

  public int perimeter() throws Exception {
        if ( radius < 0 )
                throw new Exception("Circle is not initialized");
        else
                return (int)(Math.PI * radius * radius);
  }

}

Source Code: Src/7/Circle.java

Src/7/Square.java.minusSTART_STOP


/**
 * This class implements a Square class.
 *
 * @version   $Id$
 *
 * @author    hp bischof
 *
 * Revisions:
 *      $Log$
 */

public class Square extends Area {

  private int length;   

  public Square(int _length) throws Exception {
        if ( _length < 0 )
                throw new Exception("Negative length (" +
                                length + ") is not acceptable");
        else
                length = _length;
  }

  public int area() throws Exception {
        if ( length < 0 )
                throw new Exception("Square is not initialized");
        else
                return length * length;
  }

  public int perimeter() throws Exception {
        if ( length < 0 )
                throw new Exception("Square is not initialized");
        else
                return 4 * length;
  }

}

Source Code: Src/7/Square.java

8.20.  Reading From Files

Src/7/FileIO.java.minusSTART_STOP


import java.io.*;
public class FileIO {

  static void cp(String inF, String outF )      {
        DataInputStream in;
        DataOutputStream out;

        try { 
                in = new DataInputStream(
                        new FileInputStream(inF) );
                out = new DataOutputStream(
                        new FileOutputStream(outF) );
                try {
                        do {
                                out.writeByte (in.readByte() );
                        } while ( true );
                }
                catch ( EOFException e )        {
                        in.close();
                        out.close();
                }
        }
        catch ( FileNotFoundException e )       {
                e.printStackTrace();
                System.out.println("Can't find the file!");
        }
        catch ( IOException e ) {  // Throws: IOException !!!
                e.printStackTrace();
                System.out.println("Could not be opened for writing!");
        }
        catch ( Exception e )   {
                System.out.println("Can't find the file!");
        }
  }

  public static void main(String args[]) {
        if ( args.length != 2 ) 
                System.out.println("Usage: java FileIO f1 f2");
        else    {
                System.out.println(args[0] + "  " + args[1] );
                cp(args[0], args[1]);
        }
  }
}

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!

8.21.  Exception Index

8.22.  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.

8.23.  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.

8.24.  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


/**
 * Thrown to indicate that a method has been passed
 * an illegal or inappropriate ssid.
 */

class  NumberException extends Exception
{
        /**
         * Constructs an NumberException with no detail message
         */
        public NumberException()        {
                super();
        }

        /**
         * Constructs an NumberException with Number.Exception detail message
         *
         ** @param    s    the detail message.
         */
        public NumberException(String s)        {
                super(s);
        }
}

Source Code: Src/7/NumberException.java

8.25.  Assertions

assert expression1; 
assert expression1 : expression2

8.26.  Assertions: Example

Src/7/Assertion_1.java.minusSTART_STOP


/*
 * Execetion: java -ea Assertion_1
 */
public class Assertion_1 {
        public void method( int value ) {
                assert 0 <= value;
                System.out.println("asertM ---->");
                System.out.println("\tvalue = " + value );
                System.out.println("asertM <----");
        }

        public static void main( String[] args ) {
                Assertion_1 asertM = new Assertion_1();
                asertM.method( 1 );
                asertM.method( -1 );
        }
}

Source Code: Src/7/Assertion_1.java

% javac Assertion_1.java
% java Assertion_1
asertM ---->
        value = 1
asertM <----
asertM ---->
        value = -1
asertM <----
% java -ea Assertion_1
asertM ---->
        value = 1
asertM <----
Exception in thread "main" java.lang.AssertionError
        at Assertion_1.method(Assertion_1.java:6)
        at Assertion_1.main(Assertion_1.java:15)

8.27.  Assertions: Processed

[picture]

8.28.  Assertions: Enable

% java -verbose
    ...
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    ...

8.29.  Assertions: Throwable

See also: http://www.cs.rit.edu/usr/local/j2sdk1.5.0-beta1/docs/api/index.html

8.30.  Assertions: Disableing


Weiter | Weiter | Weiter | Weiter | Kommentar


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