Chapter 9

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Appendix C.  Answers to Review Questions


A1:

You throw an exception by creating an instance of the exception class and passing it to the throw keyword. For example:

 MyException ex = new MyException( "This is my exception" );  throw ex; 

Or:

 throw new MyException( "This is my exception" ); 

A2:

You handle an exception by call any method that can throw an exception in a try block and then catching the exception in a catch block. If the method accelerate() can throw a CarException then you would handle it as follows:

 try {     accelerate();  }  catch( CarException ex ) {    ex.printStackTrace();  } 

A3:

The try keyword denotes the start of a try block; the try block contains method calls that can throw exceptions and it exists to handle those exceptions.

A4:

java.lang.Throwable

A5:

Exceptions that derive from the java.lang.Exception class.

A6:

Exceptions that derive from the java.lang.RuntimeException class.

A7:

A subclass method can only throw exceptions that are explicitly defined in its super class's method's signature. The only caveat is that it can throw an exception that is of a class type that subclasses one of the super class method's exceptions.

A8:

The throws method is used in a method's signature to define the list of exceptions that the method can throw.

A9:

These are the steps:

  1. Create a class that extends the java.lang.Exception class.

  2. In a class that will throw this exception, create a method that lists the custom exception in its throws clause.

  3. Somewhere in the method create an instance of the custom exception and throw it using the throw keyword.

A10:

Exceptions are classes because they need to be sent from one to another, possibly in a different process. The benefit to you is that you can define your own data and methods in the exception class to help better diagnose the root cause of the problem.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net