Chapter 9


Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Appendix C.  Answers to Review Questions


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; 


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


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();  } 


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.




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


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


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.


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


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.


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.


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

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: