Exception handling
Exceptions are Java objects; exception classes are derived from java.lang.Throwable.
An exception is thrown to denote an abnormal occurrence like accessing an array index that exceeds the size of the array. Exceptions can be checked or unchecked. Subclasses of RuntimeException and Error are called unchecked exceptions. All other classes, which inherit from Exception, are checked exceptions. Any method that might throw a checked exception must either declare the exception using the throws keyword or handle the exception using a try/catch block.
try/catch block
The code that might throw an exception is enclosed in the try block. One or more catch clauses can be provided to handle different exception types:
try
{
// code that might throw exceptions
}
catch(Exception e)
{
//code to handle the exception
}
The more specific exception type should be caught first. For instance, we have to order the catch blocks from specific to most general, otherwise a compile-time error occurs.
For example, assume that MyException inherits from Exception:
try
{
throw new MyException();
}
catch(Exception e)
{
System.out.println("Exception");
}
catch(MyException e)
{
System.out.println("MyException");
}
Here the compiler complains that the catch clause for MyException is unreachable because all exceptions thrown will be caught by the first general catch clause.
finally block
The finally block can also be provided to perform any cleanup operation. If an exception is thrown, any matching catch clauses are executed, then control comes to the finally block, if one is provided. The syntax of the finally block is as follows:
try
{
// code that throws exceptions
}
catch(Exception e)
{
// handle exception
}
finally
{
// cleanup code
}
The finally block is executed even if no exception is thrown. The only case in which this does not happen is when System.exit() is invoked by the try or catch blocks. A try block should have either a catch block or a finally block, but it's not required to have both.
Declaring and throwing exceptions
To throw an exception explicitly from the code, use the throw keyword.
The checked exceptions that a method can throw must be declared using the throws keyword.
For instance:
void f() throws MyException
{
if(x > y) throw new MyException(); // MyException is a subclass of Exception
}
1 comment: