EXCEPTION
An Exception is an abnormal condition that arises in a code sequence at run time, ie.
run-time error.
A java Exception is an object that describes an exceptional condition that has occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.
Method may choose to handle the exception itself or pass it on.
General for of an exception-handling block:
try{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb){
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
//…..
finally{
// block of code to be executed before try block ends
}
Exception Types
All Exception types are subclasses of the built-in class Throwable.
Two subclasses
Exception
Error
Exception is used for exceptional conditions that user program should catch.
You subclass this class to create your own custom exception types
Important subclass of Exception is RuntimeException.
Uncaught Exception
class Exc0 {
public static void main (String args[]) {
int d = 0;
int a = 42 / d;
}
}
throws Exception.
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
class Exc1 {
static void subroutine () {
int d = 0;
int a = 42 / d;
}
public static void main (String args[]) {
Exc1.subroutine();
}
}
java.lang.ArithmeticException: / by zero // call stack
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
Must be caught and dealt with immediately.
class Exc2 {
public static void main (String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println ("This will not be printed");
} catch (ArithmeticException e) {
System.out.println ("Division by zero.");
}
System.out.println ("After catch statement.");
}
OUTPUT
Division by zero.
After catch statement.
Catch is not called, so control never returns to the try block.
You can describe the Exception by passing it as an argument to println() statement.
Multiple catch clauses
Each catch statement is inspected in order they are specified.
The first one that matches the type of exception is executed.
Others are bypassed.
Execution continues after try/catch block.
class MultiCatch {
public static void main (String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a ;
int c[] ={ 1 };
c[42] = 99;
}catch (ArithmeticException e) {
System.out.println ("Divide by 0:" + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println ("Array Index oob:" + e);
}
System.out.println ("After try/catch blocks.");
}
}
subclasses must come before their superclasses.
In java, unreachable code is an error.
Nested try Statements
Class NestTry {
public static void main (String args[]) {
try {
//….
//….
try {
//…
//….
}catch (ExceptionType exOb) {
//….
}
}catch (ExceptionType exOb) {
//….
}
}
}
Each time a try block is entered, the context of that exception is pushed n the stack.
If an inner try statement does not have a catch handler for a particular exception, the stack is unwounded and next try statement’s catch handlers are inspected for a match.
Continues till 1 catch statement succeeds, or until all try statements are exhausted.
If no catch statement matches, then the Java run-time will handle the exception.
Throw
Possible for program to explicitly throw exception
throw ThrowableInstance
ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
2 ways to obtain Throwable object:
Using a parameter into a catch clause
Creating one with a new operator.
try {
throw new NullPointerException("created");
}catch (NullPointerException e) {
throw e; //rethrow the Exception
}
throws
If a method is capable of causing an exception that it does not handle, it must specify this behaviour so that callers of the method can guard themselves against that exception.
type method-name(paramlist) throws exception-list
{
//…..
}
throws clause lists the types of exceptions that a method might throw.
Necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.
finally
Whenexceptions are thrown, execution in the method takes rather abrupt, nonlinear path that alters the normal flow through the method.
finally creates a block of code that will be executed after try/catch block has completed and before the code following try/catch block.
Will execute whether or not the exception is thrown.
Can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of the method with the intent of disposing of them before returning.
Java’ Biult-in Exceptions
java.lang defines several exception classes.
Checked and Unchecked Exceptions
java.lang implicitly imported.
So, most Exceptions derived from RuntimeException are automatically available.
They need not be specified in a methods throws list.
Are called unchecked Exceptions, as compiler does not check to see if a method handles or throws these exceptions.
Unchecked RuntimeException Subclasses
ArithmeticException
ArrayIndexOutOfBoundsException
ArraStoreException
ClassCastException
IllegalArgumentException
IllegalMonitorStateException
IllegalStateException
IllegalThreadStateException
IndexOutOfBoundsException
NegativeArraySizeException
NullPointerException
NumberFormatException
SecurityException
StringIndexOutOfBounds
UnsupportedOperationException
Java’s Checked Exceptions in java.lang
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
Creating your own Exception Subclasses
Class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[ " + detail " ]";
}
}
class ExceptionDemo {
static void compute( int a) throws MyException {
if (a > 10)
throw new MyException(a);
System.out.println("Normal Exit");
}
public static void main (String args[]) {
try {
compute(1);
compute(50);
}catch (MyException e) {
//…..
}
}
}