L24 Exception Handling
L24 Exception Handling
Exception Handling
By
Arvind Kumar
Asst. Professor, LPU
Introduction
• An exception is an abnormal condition that arises in a code
sequence at run time.
• Exceptions of this type are automatically defined for the programs that we
write and include things such as division by zero and invalid array indexing.
• Each exception is a run-time error but all run-time errors are not exceptions.
Throwable
Exception Error
Unchecked Exception
• Unchecked Exceptions are those that are not forced by the
compiler either to be caught or to be thrown.
• ArrayIndexOutOfBoundsException
• NumberFormatException
• IOException
Commonly used sub-classes of Errors
• StackOverFlowError
• NoClassDefFoundError
• NoSuchMethodError
Uncaught Exceptions
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
• When the Java run-time system detects the attempt to divide by zero,
it constructs a new exception object and then throws this exception.
• once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately.
• In the previous example, we haven’t supplied any exception handlers
of our own.
• catch
• throw
• throws
• finally
Why Exception Handling?
• When the default exception handler is provided by the Java
run-time system , why Exception Handling?
try {
Statements whose execution may cause an exception
}
Note: try block is always used either with catch or finally or with
both.
Keywords for Exception Handling
catch:
• catch is used to define a handler.
catch (NumberFormatException n)
{System.out.println(“Arguments must be Numeric”);}
catch (ArrayIndexOutOfBoundsException a)
{System.out.println(“Invalid Number of arguments”);}
}
}
Nested try Statements
• A try statement can be inside the block of another try.
Finally
• finally creates a block of code that will be executed after a
try/catch block has completed and before the code following
the try/catch block.
• The Exception class does not define any methods of its own.
• Exception( )
• Exception(String msg)