Java Tutorial/Exception Handling

From Wikiversity
Jump to navigation Jump to search

What are exceptions?[edit | edit source]

An exception is a runtime error event that occurs in the normal process flow of a program. In Java these exceptions are also classes and are usually instantiated when an error occurs. The following code shows a simple example of exception use:

try {
    File f = new File (fileName);
    readFile (f);   
catch (FileNotFoundException ex) {
    System.err.println ("There is no such file: " + fileName);
finally {
    closeFile (); // close the file after it has been read or after the exception has been caught 

What are checked exceptions?[edit | edit source]

All exceptions that are neither RuntimeExceptions nor Errors are checked exceptions, which means the exception is part of the method's signature, like the parameters of a method and its return type. A Java program will not compile if the checked exceptions its methods throw are not properly handled by the calling methods. In the example above this would mean not handling the FileNotFoundException would cause a compile time error. Modern development environments display these errors already inside the editor and a compilation is not required to find the error.

Why they need to be handled?[edit | edit source]

Exceptions, or errors, need to be handled or the user will get a runtime error. Below are some examples of handling exceptions.

Different ways[edit | edit source]

Adding "throws" expression[edit | edit source]

Using try/catch block[edit | edit source]

The try/catch block will try to do the wanted action. If an error occurs, It executes the catch section instead. The syntax is

try {
//Java code...
} catch {
//Java code...

What happens in exception handling?[edit | edit source]