Exception Handling in Java

What is an Exception?

An exception is an object that represents an error or an exceptional situation that has occurred

Exception categories in Java

Java has two primary kinds of exceptions

When to use Exceptions

How do you do exception handling?

The process involves:

Claiming Exceptions

In a Java method claim an exception with the keyword throws. This goes at the end of the method's prototype and before the definition. Multiple exceptions can be claimed, with a comma-separated list. Examples:
  public void myMethod() throws IOException

  public void yourMethod() throws IOException, AWTException, BobException

Throwing Exceptions

In Java, use the keyword throw, along with the type of exception being thrown. An exception is an object, so it must be created with the new operator. It can be created within the throw statement or before it. Examples:
  throw new BadHairDayException();

  MyException m = new MyException();
  throw m;

  if (personOnPhone != bubba)
     throw new Exception("Stranger on the phone!!");
Note that this is different than the keyword throws, which is used in claiming exceptions.

Catching Exceptions

Keywords: try, catch, finally

Trivial Example

Example Layout -- try, catch, finally

 try
 {
    // lots of IO code opening and reading from/to files
 }
 catch (FileNotFoundException)
 {
    // tell the user and probably repeat try block
 }
 catch (EOFException)
 {
    // hit the End Of File marker early
 }
 catch (IOException)
 {
    // blanket catch for all other IO problems
 }
 finally
 {
    // make sure to close any files that might be open
 }

What happens if an exception is not caught?

Instance methods in exception objects

Exception objects are created from classes, which can have instance methods. There are some special instance methods that all exception objects have (inherited from Throwable):

Deitel code examples in Chapter 13 folder


Exception Handling in C++

While the concepts are largely the same, the syntax differs a little