What is an exception explain various causes of exceptions?

An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program. Abnormality do occur when your program is running. For example, you might expect the user to enter an integer, but receive a text string; or an unexpected I/O error pops up at runtime. What really matters is "what happens after an abnormality occurred?" In other words, "how the abnormal situations are handled by your program." If these exceptions are not handled properly, the program terminates abruptly and may cause severe consequences. For example, the network connections, database connections and files may remain opened; database and file records may be left in an inconsistent state.

Java has a built-in mechanism for handling runtime errors, referred to as exception handling. This is to ensure that you can write robust programs for mission-critical applications.

Older programming languages such as C have some drawbacks in exception handing. For example, suppose the programmer wishes to open a file for processing:

  1. The programmers are not made to aware of the exceptional conditions. For example, the file to be opened may not necessarily exist. The programmer therefore did not write codes to test whether the file exists before opening the file.
  2. Suppose the programmer is aware of the exceptional conditions, he/she might decide to finish the main logic first, and write the exception handling codes later – this "later", unfortunately, usually never happens. In other words, you are not force to write the exception handling codes together with the main logic.
  3. Suppose the programmer decided to write the exception handling codes, the exception handling codes intertwine with the main logic in many if-else statements. This makes main logic hard to follow and the entire program hard to read. For example,
    if (file exists) {
       open file;
       while (there is more records to be processed) {
          if (no IO errors) {
             process the file record
          } else {
             handle the errors
          }
       }
       if (file is opened) close the file;
    } else {
       report the file does not exist;
    }

Java overcomes these drawbacks by building the exception handling into the language rather than leaving it to the discretion of the programmers:

  1. You will be informed of the exceptional conditions that may arise in calling a method - Exceptions are declared in the method's signature.
  2. You are forced to handle exceptions while writing the main logic and cannot leave them as an afterthought - Your program cannot compiled without the exception handling codes.
  3. Exception handling codes are separated from the main logic - Via the
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    3 construct.

Let's look into these three points in more details.

Point 1: Exceptions must be Declared

As an example, suppose that you want to use a

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
4 to perform formatted input from a disk file. The signature of the
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
5's constructor with a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
6 argument is given as follows:

public Scanner(File source) throws FileNotFoundException;

The method's signature informs the programmers that an exceptional condition "file not found" may arise. By declaring the exceptions in the method's signature, programmers are made to aware of the exceptional conditions in using the method.

Point 2: Exceptions must be Handled

If a method declares an exception in its signature, you cannot use this method without handling the exception - you can't compile the program.

Example 1: The program did not handle the exception declared, resutled in compilation error.

ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^

To use a method that declares an exception in its signature, you MUST either:

  1. provide exception handling codes in a "
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    7" or "
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    3" construct, or
  2. not handling the exception in the current method, but declare the exception to be thrown up the call stack for the next higher-level method to handle.

Example 2: Catch the exception via a "

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
7" (or "
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
3") construct.

If the file cannot be found, the exception is caught in the catch-block. In this example, the error handler simply prints the stack trace, which provides useful information for debugging. In some situations, you may need to perform some clean-up operations, or open another file instead. Take note that the main logic in the try-block is separated from the error handling codes in the catch-block.

Example 3: You decided not to handle the exception in the current method, but throw the exception up the call stack for the next higher-level method to handle.

In this example, you decided not to handle the

public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
1 thrown by the
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
2 method (with
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
7). Instead, the caller of
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
2 - the
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
5 method - declares in its signature "
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
6", which means that this exception will be thrown up the call stack, for the next higher-level method to handle. In this case, the next higher-level method of
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
5 is the JVM, which simply terminates the program and prints the stack trace.

Point 3: Main logic is separated from the exception handling codes

As shown in Example 2, the main logic is contained in the try-block, while the exception handling codes are kept in the catch-block(s) separated from the main logic. This greatly improves the readability of the program.

For example, a Java program for file processing could be as follows:

Method Call Stack

A typical application involves many levels of method calls, which is managed by a so-called method call stack. A stack is a last-in-first-out queue. In the following example,

public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
5 method invokes
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
9;
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
9 calls
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
1;
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
1 calls
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
What is an exception explain various causes of exceptions?

As seen from the output, the sequence of events is:

  1. JVM invoke the
    public class MethodCallStackDemo {
       public static void main(String[] args) {
          System.out.println("Enter main()");
          methodA();
          System.out.println("Exit main()");
       }
     
       public static void methodA() {
          System.out.println("Enter methodA()");
          methodB();
          System.out.println("Exit methodA()");
       }
     
       public static void methodB() {
          System.out.println("Enter methodB()");
          methodC();
          System.out.println("Exit methodB()");
       }
     
       public static void methodC() {
          System.out.println("Enter methodC()");
          System.out.println("Exit methodC()");
       }
    }
    5.
  2. public class MethodCallStackDemo {
       public static void main(String[] args) {
          System.out.println("Enter main()");
          methodA();
          System.out.println("Exit main()");
       }
     
       public static void methodA() {
          System.out.println("Enter methodA()");
          methodB();
          System.out.println("Exit methodA()");
       }
     
       public static void methodB() {
          System.out.println("Enter methodB()");
          methodC();
          System.out.println("Exit methodB()");
       }
     
       public static void methodC() {
          System.out.println("Enter methodC()");
          System.out.println("Exit methodC()");
       }
    }
    5 pushed onto call stack, before invoking
    public class MethodCallStackDemo {
       public static void main(String[] args) {
          System.out.println("Enter main()");
          methodA();
          System.out.println("Exit main()");
       }
     
       public static void methodA() {
          System.out.println("Enter methodA()");
          methodB();
          System.out.println("Exit methodA()");
       }
     
       public static void methodB() {
          System.out.println("Enter methodB()");
          methodC();
          System.out.println("Exit methodB()");
       }
     
       public static void methodC() {
          System.out.println("Enter methodC()");
          System.out.println("Exit methodC()");
       }
    }
    9.
  3. public class MethodCallStackDemo {
       public static void main(String[] args) {
          System.out.println("Enter main()");
          methodA();
          System.out.println("Exit main()");
       }
     
       public static void methodA() {
          System.out.println("Enter methodA()");
          methodB();
          System.out.println("Exit methodA()");
       }
     
       public static void methodB() {
          System.out.println("Enter methodB()");
          methodC();
          System.out.println("Exit methodB()");
       }
     
       public static void methodC() {
          System.out.println("Enter methodC()");
          System.out.println("Exit methodC()");
       }
    }
    9 pushed onto call stack, before invoking
    Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    1.
  4. Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    1 pushed onto call stack, before invoking
    Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    3.
  5. Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    3 completes.
  6. Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    1 popped out from call stack and completes.
  7. public class MethodCallStackDemo {
       public static void main(String[] args) {
          System.out.println("Enter main()");
          methodA();
          System.out.println("Exit main()");
       }
     
       public static void methodA() {
          System.out.println("Enter methodA()");
          methodB();
          System.out.println("Exit methodA()");
       }
     
       public static void methodB() {
          System.out.println("Enter methodB()");
          methodC();
          System.out.println("Exit methodB()");
       }
     
       public static void methodC() {
          System.out.println("Enter methodC()");
          System.out.println("Exit methodC()");
       }
    }
    9 popped out from the call stack and completes.
  8. public class MethodCallStackDemo {
       public static void main(String[] args) {
          System.out.println("Enter main()");
          methodA();
          System.out.println("Exit main()");
       }
     
       public static void methodA() {
          System.out.println("Enter methodA()");
          methodB();
          System.out.println("Exit methodA()");
       }
     
       public static void methodB() {
          System.out.println("Enter methodB()");
          methodC();
          System.out.println("Exit methodB()");
       }
     
       public static void methodC() {
          System.out.println("Enter methodC()");
          System.out.println("Exit methodC()");
       }
    }
    5 popped out from the call stack and completes. Program exits.

suppose that we modify

Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
3 to carry out a "divide-by-0" operation, which triggers a
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)
        at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)
        at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10)
        at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
6:

The exception message clearly shows the method call stack trace with the relevant statement line numbers:

Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)
        at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)
        at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10)
        at MethodCallStackDemo.main(MethodCallStackDemo.java:4)

Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)
        at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)
        at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10)
        at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
7 triggers an
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)
        at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)
        at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10)
        at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
6. As it does not handle this exception, it popped off from the call stack immediately.
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)
        at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)
        at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10)
        at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
9 also does not handle this exception and popped off the call stack. So does
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
9 and
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
5 method. The
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
5 method passes back to JVM, which abruptly terminates the program and print the call stack trace, as shown.

Exception & Call Stack

What is an exception explain various causes of exceptions?

When an exception occurs inside a Java method, the method creates an

public void methodD() throws XxxException, YyyException { ...... }
3 object and passes the
public void methodD() throws XxxException, YyyException { ...... }
3 object to the JVM (in Java term, the method "
public void methodD() throws XxxException, YyyException { ...... }
5" an
public void methodD() throws XxxException, YyyException { ...... }
3). The
public void methodD() throws XxxException, YyyException { ...... }
3 object contains the type of the exception, and the state of the program when the exception occurs. The JVM is responsible for finding an exception handler to process the
public void methodD() throws XxxException, YyyException { ...... }
3 object. It searches backward through the call stack until it finds a matching exception handler for that particular class of
public void methodD() throws XxxException, YyyException { ...... }
3 object (in Java term, it is called "
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0" the
public void methodD() throws XxxException, YyyException { ...... }
3). If the JVM cannot find a matching exception handler in all the methods in the call stack, it terminates the program.

This process is illustrated as follows. Suppose that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2 encounters an abnormal condition and throws a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3 to the JVM. The JVM searches backward through the call stack for a matching exception handler. It finds
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
9 having a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3 handler and passes the exception object to the handler. Notice that
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
3 and
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
1 are required to declare "
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
8 in their method signatures in order to compile the program.

Exception Classes - Throwable, Error, Exception & RuntimeException

The figure ‎below shows the hierarchy of the

public void methodD() throws XxxException, YyyException { ...... }
3 classes. The base class for all
public void methodD() throws XxxException, YyyException { ...... }
3 objects is
Start of the main logic
Try opening a file ...
File Not Found caught ...
finally-block runs regardless of the state of exception
After try-catch-finally, life goes on...
1, together with its two subclasses
Start of the main logic
Try opening a file ...
File Not Found caught ...
finally-block runs regardless of the state of exception
After try-catch-finally, life goes on...
2 and
Start of the main logic
Try opening a file ...
File Not Found caught ...
finally-block runs regardless of the state of exception
After try-catch-finally, life goes on...
3.

What is an exception explain various causes of exceptions?
  • The
    Start of the main logic
    Try opening a file ...
    File Not Found caught ...
    finally-block runs regardless of the state of exception
    After try-catch-finally, life goes on...
    4 class describes internal system errors (e.g.,
    Start of the main logic
    Try opening a file ...
    File Not Found caught ...
    finally-block runs regardless of the state of exception
    After try-catch-finally, life goes on...
    5,
    Start of the main logic
    Try opening a file ...
    File Not Found caught ...
    finally-block runs regardless of the state of exception
    After try-catch-finally, life goes on...
    6) that rarely occur. If such an error occurs, there is little that you can do and the program will be terminated by the Java runtime.
  • The
    public void methodD() throws XxxException, YyyException { ...... }
    3 class describes the error caused by your program (e.g.
    public class MethodCallStackDemo {
       public static void main(String[] args) {
          System.out.println("Enter main()");
          methodA();
          System.out.println("Exit main()");
       }
     
       public static void methodA() {
          System.out.println("Enter methodA()");
          methodB();
          System.out.println("Exit methodA()");
       }
     
       public static void methodB() {
          System.out.println("Enter methodB()");
          methodC();
          System.out.println("Exit methodB()");
       }
     
       public static void methodC() {
          System.out.println("Enter methodC()");
          System.out.println("Exit methodC()");
       }
    }
    1,
    Start of the main logic
    Try opening a file ...
    File Not Found caught ...
    finally-block runs regardless of the state of exception
    After try-catch-finally, life goes on...
    9). These errors could be caught and handled by your program (e.g., perform an alternate action or do a graceful exit by closing all the files, network and database connections).

Checked vs. Unchecked Exceptions

As illustrated, the subclasses of

Start of the main logic
Try opening a file ...
File Not Found caught ...
finally-block runs regardless of the state of exception
After try-catch-finally, life goes on...
4 and
public Scanner(File source) throws FileNotFoundException;
01 are known as unchecked exceptions. These exceptions are not checked by the compiler, and hence, need not be caught or declared to be thrown in your program. This is because there is not much you can do with these exceptions. For example, a "divide by 0" triggers an
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)
        at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)
        at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10)
        at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
6, array index out-of-bound triggers an
public Scanner(File source) throws FileNotFoundException;
03 which are really programming logical errors that shall be been fixed in compiled-time, rather than leaving it to runtime exception handling.

All the other exception are called checked exceptions. They are checked by the compiler and must be caught or declared to be thrown.

Exception Handling Operations

Five keywords are used in exception handling:

public Scanner(File source) throws FileNotFoundException;
04,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0,
public Scanner(File source) throws FileNotFoundException;
06,
public Scanner(File source) throws FileNotFoundException;
07 and
public void methodD() throws XxxException, YyyException { ...... }
5 (take note that there is a difference between
public void methodD() throws XxxException, YyyException { ...... }
5 and
public Scanner(File source) throws FileNotFoundException;
07).

Java’s exception handling consists of three operations:

  1. Declaring exceptions;
  2. Throwing an exception; and
  3. Catching an exception.
Declaring Exceptions

A Java method must declare in its signature the types of checked exception it may "throw" from its body, via the keyword "throws".

For example, suppose that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2 is defined as follows:

The method's signature indicates that running

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2 may encounter two checked exceptions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3 and
public Scanner(File source) throws FileNotFoundException;
14. In other words, some of the abnormal conditions inside
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2 may trigger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3 or
public Scanner(File source) throws FileNotFoundException;
14.

Exceptions belonging to

Start of the main logic
Try opening a file ...
File Not Found caught ...
finally-block runs regardless of the state of exception
After try-catch-finally, life goes on...
4,
public Scanner(File source) throws FileNotFoundException;
01 and their subclasses need not be declared. These exceptions are called unchecked exceptions because they are not checked by the compiler.

Throwing an Exception

When a Java operation encounters an abnormal situation, the method containing the erroneous statement shall create an appropriate

public void methodD() throws XxxException, YyyException { ...... }
3 object and throw it to the Java runtime via the statement "
public Scanner(File source) throws FileNotFoundException;
21". For example,

Note that the keyword to declare exception in the method's signature is "

public Scanner(File source) throws FileNotFoundException;
07" and the keyword to throw an exception object within the method's body is "
public void methodD() throws XxxException, YyyException { ...... }
5".

Catching an Exception

When a method throws an exception, the JVM searches backward through the call stack for a matching exception handler. Each exception handler can handle one particular class of exception. An exception handler handles a specific class can also handle its subclasses. If no exception handler is found in the call stack, the program terminates.

For example, suppose

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2 declares that it may throw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3 and
public Scanner(File source) throws FileNotFoundException;
14 in its signature, as follows:

public void methodD() throws XxxException, YyyException { ...... }

To use

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2 in your program (says in
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exit methodC()
Exit methodB()
Exit methodA()
Exit main()
3), you can either:

  1. Wrap the call of
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    2 inside a try-catch (or try-catch-finally) as follows. Each catch-block can contain an exception handler for one type of exception.
  2. Suppose that
    Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    3 who calls
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    2 does not wish to handle the exceptions (via a try-catch), it can declare these exceptions to be thrown up the call stack in its signature as follows: In this case, if a
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    3 or
    public Scanner(File source) throws FileNotFoundException;
    14 is thrown by
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    2, JVM will terminate
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    2 as well as
    Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    3 and pass the exception object up the call stack to the caller of
    Enter main()
    Enter methodA()
    Enter methodB()
    Enter methodC()
    Exit methodC()
    Exit methodB()
    Exit methodA()
    Exit main()
    3.

try-catch-finally

The syntax of try-catch-finally is:

If no exception occurs during the running of the try-block, all the catch-blocks are skipped, and finally-block will be executed after the try-block. If one of the statements in the try-block throws an exception, the Java runtime ignores the rest of the statements in the try-block, and begins searching for a matching exception handler. It matches the exception type with each of the catch-blocks sequentially. If a catch-block catches that exception class or catches a superclass of that exception, the statement in that catch-block will be executed. The statements in the finally-block are then executed after that catch-block. The program continues into the next statement after the try-catch-finally, unless it is pre-maturely terminated or branch-out.

If none of the
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0-block matches, the exception will be passed up the call stack. The current method executes the
public Scanner(File source) throws FileNotFoundException;
06 clause (if any) and popped off the call stack. The caller follows the same procedures to handle the exception.

The

public Scanner(File source) throws FileNotFoundException;
06 block is almost certain to be executed, regardless of whether or not exception occurs (unless JVM encountered a severe error or a
public Scanner(File source) throws FileNotFoundException;
41 is called in the
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0 block).

Example 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

This is the output when the

public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
1 triggered:

Start of the main logic
Try opening a file ...
File Not Found caught ...
finally-block runs regardless of the state of exception
After try-catch-finally, life goes on...

This is the output when no exception triggered:

public Scanner(File source) throws FileNotFoundException;
0
Example 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public Scanner(File source) throws FileNotFoundException;
2
try-catch-finally
  • A try-block must be accompanied by at least one catch-block or a finally-block.
  • You can have multiple catch-blocks. Each catch-block catches only one type of exception.
  • A catch block requires one argument, which is a
    public Scanner(File source) throws FileNotFoundException;
    44 object (i.e., a subclass of
    Start of the main logic
    Try opening a file ...
    File Not Found caught ...
    finally-block runs regardless of the state of exception
    After try-catch-finally, life goes on...
    1), as follows:
  • You can use the following methods to retrieve the type of the exception and the state of the program from the
    public Scanner(File source) throws FileNotFoundException;
    46 object:
    • public Scanner(File source) throws FileNotFoundException;
      47: Prints this
      public Scanner(File source) throws FileNotFoundException;
      46 and its call stack trace to the standard error stream
      public Scanner(File source) throws FileNotFoundException;
      49. The first line of the outputs contains the result of
      public Scanner(File source) throws FileNotFoundException;
      50, and the remaining lines are the stack trace. This is the most common handler, if there is nothing better that you can do. For example, You can also use
      public Scanner(File source) throws FileNotFoundException;
      51 or
      public Scanner(File source) throws FileNotFoundException;
      52.
    • public Scanner(File source) throws FileNotFoundException;
      53: Returns the
      public Scanner(File source) throws FileNotFoundException;
      54 specified if the object is constructed using constructor
      public Scanner(File source) throws FileNotFoundException;
      55.
    • public Scanner(File source) throws FileNotFoundException;
      50: Returns a short description of this
      public Scanner(File source) throws FileNotFoundException;
      46 object, consists of the name of the class, a colon
      public Scanner(File source) throws FileNotFoundException;
      58, and a message from
      public Scanner(File source) throws FileNotFoundException;
      53.
  • A catch block catching a specific exception class can also catch its subclasses. Hence,
    public Scanner(File source) throws FileNotFoundException;
    60 catches all kinds of exceptions. However, this is not a good practice as the exception handler that is too general may unintentionally catches some subclasses' exceptions it does not intend to.
  • The order of catch-blocks is important. A subclass must be caught (and placed in front) before its superclass. Otherwise, you receive a compilation error "exception
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    3 has already been caught".
  • The finally-block is meant for cleanup code such as closing the file, database connection regardless of whether the try block succeeds. The finally block is always executed (unless the catch-block pre-maturely terminated the current method).
What if I really don't care about the exceptions

Certainly not advisable other than writing toy programs. But to bypass the compilation error messages triggered by methods declaring unchecked exceptions, you could declare "

public Scanner(File source) throws FileNotFoundException;
62" in your
public class MethodCallStackDemo {
   public static void main(String[] args) {
      System.out.println("Enter main()");
      methodA();
      System.out.println("Exit main()");
   }
 
   public static void methodA() {
      System.out.println("Enter methodA()");
      methodB();
      System.out.println("Exit methodA()");
   }
 
   public static void methodB() {
      System.out.println("Enter methodB()");
      methodC();
      System.out.println("Exit methodB()");
   }
 
   public static void methodC() {
      System.out.println("Enter methodC()");
      System.out.println("Exit methodC()");
   }
}
5 (and other methods), as follows:

Overriding and Overloading Methods

An overriding method must have the same argument list and return-type (or subclass of its original from JDK 1.5). An overloading method must have different argument list, but it can have any return-type.

An overriding method cannot have more restricted access. For example, a method with

public Scanner(File source) throws FileNotFoundException;
64 access may be overridden to have protected or public access but not
public Scanner(File source) throws FileNotFoundException;
65 or default access. This is because an overridden method is considered to be a replacement of its original, hence, it cannot be more restrictive.

An overriding method cannot declare exception types that were not declared in its original. However, it may declare exception types are the same as, or subclass of its original. It needs not declare all the exceptions as its original. It can throw fewer exceptions than the original, but not more.

An overloading method must be differentiated by its argument list. It cannot be differentiated by the return-type, the exceptions, and the modifier, which is illegal. It can have any return-type, access modifier, and exceptions, as long as it can be differentiated by the argument list.

Common Exception Classes

ArrayIndexOutOfBoundsException: thrown by JVM when your code uses an array index, which is is outside the array's bounds. For example,

public Scanner(File source) throws FileNotFoundException;
3
public Scanner(File source) throws FileNotFoundException;
4

NullPointerException: thrown by the JVM when your code attempts to use a null reference where an object reference is required. For example,

public Scanner(File source) throws FileNotFoundException;
5
public Scanner(File source) throws FileNotFoundException;
6

NumberFormatException: Thrown programmatically (e.g., by

public Scanner(File source) throws FileNotFoundException;
66) when an attempt is made to convert a string to a numeric type, but the string does not have the appropriate format. For example,

public Scanner(File source) throws FileNotFoundException;
7
public Scanner(File source) throws FileNotFoundException;
8

ClassCastException: thrown by JVM when an attempt is made to cast an object reference fails. For example,

public Scanner(File source) throws FileNotFoundException;
9
ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
0

IllegalArgumentException: thrown programmatically to indicate that a method has been passed an illegal or inappropriate argument. You could re-use this exception for your own methods.

IllegalStateException: thrown programmatically when a method is invoked and the program is not in an appropriate state for that method to perform its task. This typically happens when a method is invoked out of sequence, or perhaps a method is only allowed to be invoked once and an attempt is made to invoke it again.

NoClassDefFoundError: thrown by the JVM or class loader when the definition of a class cannot be found. Prior to JDK 1.7, you will see this exception call stack trace if you try to run a non-existent class. JDK 1.7 simplifies the error message to "Error: Could not find or load main class xxx".

Creating Your Own Exception Classes

You should try to reuse the

public void methodD() throws XxxException, YyyException { ...... }
3 classes provided in the JDK, e.g.,
public Scanner(File source) throws FileNotFoundException;
68,
Enter main()
Enter methodA()
Enter methodB()
Enter methodC()
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)
        at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)
        at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10)
        at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
6,
Start of the main logic
Try opening a file ...
File Not Found caught ...
finally-block runs regardless of the state of exception
After try-catch-finally, life goes on...
9, and
public Scanner(File source) throws FileNotFoundException;
71. But you can always create you own
public void methodD() throws XxxException, YyyException { ...... }
3 classes by extending from the class
public void methodD() throws XxxException, YyyException { ...... }
3 or one of its subclasses.

Note that

public Scanner(File source) throws FileNotFoundException;
01 and its subclasses are not checked by the compiler and need not be declared in the method's signature. Therefore, use them with care, as you will not be informed and may not be aware of the exceptions that may occur by using that method (and therefore do not have the proper exception handling codes) – a bad software engineering practice.

Example
ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
1

The output is as follows:

ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
2

Assertion (JDK 1.4)

JDK 1.4 introduced a new keyword called

public Scanner(File source) throws FileNotFoundException;
75, to support the so-called assertion feature. Assertion enables you to test your assumptions about your program logic (such as pre-conditions, post-conditions, and invariants). Each assertion contains a boolean expression that you believe will be true when the program executes. If it is not true, the JVM will throw an
public Scanner(File source) throws FileNotFoundException;
76. This error signals you that you have an invalid assumption that needs to be fixed. Assertion is much better than using if-else statements, as it serves as proper documentation on your assumptions, and it does not carry performance liability in the production environment (to be discussed later).

The

public Scanner(File source) throws FileNotFoundException;
75 statement has two forms:

ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
3

When the runtime execute the assertion, it first evaluates the

public Scanner(File source) throws FileNotFoundException;
78. If the value is
public Scanner(File source) throws FileNotFoundException;
79, nothing happens. If it is
public Scanner(File source) throws FileNotFoundException;
80, the runtime throws an
public Scanner(File source) throws FileNotFoundException;
76, using the no-argument constructor (in the first form) or
public Scanner(File source) throws FileNotFoundException;
82 as the argument to the constructor (in the second form). If an object is passed as the
public Scanner(File source) throws FileNotFoundException;
83, the object's
public Scanner(File source) throws FileNotFoundException;
50 will be called to obtain the message string.

Assertion is useful in detecting bugs. It also serves to document the inner workings of you program (e.g., pre-conditions and post-conditions) and enhances the maintainability.

One good candidate for assertion is the switch-case statement where the programmer believes that one of the cases will be selected, and the default-case is not plausible. For example,

ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
4

Assertion, by default, are disabled to ensure that they are not a performance liability in the production environment. To enable assertion, use the runtime command-line option

public Scanner(File source) throws FileNotFoundException;
85 (or
public Scanner(File source) throws FileNotFoundException;
86).

In the above example, "

public Scanner(File source) throws FileNotFoundException;
87" always triggers an
public Scanner(File source) throws FileNotFoundException;
76. However, the output is different, depending on whether assertion is enabled or disabled.

ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
5
ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
6
ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
7
ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
8

In the above example, since the "

public Scanner(File source) throws FileNotFoundException;
87" always triggers an
public Scanner(File source) throws FileNotFoundException;
76, you could choose to
public void methodD() throws XxxException, YyyException { ...... }
5 an
public Scanner(File source) throws FileNotFoundException;
76. "
public void methodD() throws XxxException, YyyException { ...... }
5" is always enabled during runtime.

ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
9

Another usage of assertion is to assert "internal invariants". In other words, to assert the possible values of an internal variable. For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2

Assertion can be used for verifying:

  • Internal Invariants: Assert that a value is within a certain constraint, e.g.,
    public Scanner(File source) throws FileNotFoundException;
    94.
  • Class Invariants: Assert that an object's state is within a constraint. What must be true about each instance of a class before or after the execution of a method? Class invariants are typically verified via
    public Scanner(File source) throws FileNotFoundException;
    95 method, e.g., an
    public Scanner(File source) throws FileNotFoundException;
    96 method to check if a
    public Scanner(File source) throws FileNotFoundException;
    97 object has a positive radius.
  • Control-Flow Invariants: Assert that a certain location will not be reached. For example, the
    public Scanner(File source) throws FileNotFoundException;
    98 clause of a
    public Scanner(File source) throws FileNotFoundException;
    99 statement.
  • Pre-conditions of methods: What must be true when a method is invoked? Typically expressed in terms of the method's arguments or the states of its objects.
  • Post-conditions of methods: What must be true after a method completes successfully?
Pre-conditions of public methods

Assertion should not be used to check the validity of the arguments (pre-condition) passed into "public" method. It is because

ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
00 methods are exposed and anyone could call this method with an invalid argument. Instead, use a
ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
01 statement to check the argument and throw an
ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      Scanner in = new Scanner(new File("test.in"));
                   ^
02 otherwise. On the other hand,
public Scanner(File source) throws FileNotFoundException;
65 methods are under your sole control and it is appropriate to assert the pre-conditions. For example,

What is exception and what are the causes of exception?

An exception is thrown for one of three reasons: An abnormal execution condition was synchronously detected by the Java virtual machine. Such conditions arise because: evaluation of an expression violates the normal semantics of the language, such as an integer divide by zero, as summarized in §15.6.

What is called exception?

An exception is something that is left out or not done on purpose. An exception to a rule does not follow that rule. This word is used for all sorts of things that are not usual or usually allowed. The saying ”i before e except after c,” is about an exception to a spelling rule.

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.

What is an exception answer?

Explanation: The problems that might occur during execution of a program are known as exceptions. The exceptions are unexpected sometimes and can be predicted. Also, the exceptions should be always considered for a better program.