An introduction to exceptions

The Throwable hierarchy:

  • Throwable
    • Error
      • Unchecked errors
    • Exception
      • RuntimeException
        • Unchecked exceptions
      • Checked exceptions

Common checked exceptions:

  • ClassNotFoundException
  • IOException
    • EOFException
    • FileNotFoundException
  • NoSuchMethodException

Common unchecked exceptions:

  • ArithmeticException
  • IllegalArgumentException
    • NumberFormatException
  • IndexOutOfBoundsException
    • ArrayIndexOutOfBoundsException
    • StringIndexOutOfBoundsException
  • NullPointerException

Method Description
Throwable() Create a new exception with a null message.
Throwable(message) Create a new exception with the specified message.

Method Description
getMessage() Returns the message associated with the exception, if one is available.
printStackTrace() Prints the stack trace to the standard error out stream along with the value of the toString method of the exception object.
toString() Returns a short description of this throwable

CODE example of an Extended Exception

public class QBWexception extends Exception
{
public QBWexception()
{
}
public QBWexception(String message)
{
super(message);
}
}

CODE example of TRY, CATCH and FINALLY:

public class Exceptions
{
public static void main(String args[])
{
try
{
System.out.println(”Try Block before the error.”);

System.out.println(1/0);
System.out.println(”Try Block after the error.”); //this line will not print
}
catch(java.lang.ArithmeticException e)
{
System.out.println(”Catch Block”);
System.out.println(”A Stack Trace of the Error:”);
e.printStackTrace();

//e.getMessage(); //This one is useable when we write our own exceptions

System.out.println(”The operation is not possible.”);
}

finally
{
System.out.println(”Finally Block”);
}
}
}
Your output should be:

*
Try Block before the error.
Catch Block
A Stack Trace of the Error:
java.lang.ArithmeticException: / by zero
at Exceptions.main(Exceptions.java:5)
The operation is not possible.
Finally Block
*

More details can be found at: http://www.j2ee.me/javase/6/docs/api/java/lang/Throwable.html