Java Tutorial/Exception Handling
What are exceptions?
editAn 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?
editAll 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?
editExceptions, or errors, need to be handled or the user will get a runtime error. Below are some examples of handling exceptions.
Different ways
editAdding "throws" expression
editUsing try/catch block
editThe 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...
}