Professional Documents
Culture Documents
Exception Handling
• Exception is a runtime error
(OR)
• abnormal condition that arises in code sequence at runtime
• Java Run Time (JRT) creates an object and throws in method that
caused the error
• Two sub classes for Throwable class they are Exception class
and Error class
Throwable
Exception Error
RuntimeException
• RuntimeException are automatically defined for the programs
• (i.e. Division by zero & Invalid Array indexing)
Errors
• Exception that are not expected under normal circumstances are
Errors
• Exception are created by JRT and thrown automatically which is handled by Exc0
• We have not specified any exception handlers and hence default handler used by
JRT
Using try and catch
• Usage of Exception handlers will help fix errors and prevent programs from
automatic termination. Example below
class Exc2 {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
throw Clause
• Java Runtime uses throw clause to throw exception explicitly
throw ThrowableIntance;
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e;
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
Caught inside demoproc.
} Recaught: java.lang.NullPointerException: demo
}
}
throws clause
• Methods not capable of handling specific type of errors
Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}
• throws are not used with Error and RuntimeException and its
subclasses
throws clause - Example
class ThrowsDemo {
static void throwOne() throws IllegalAccessException{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
finally clause
• finally executes after try or catch block has completed
• Example:
User Defined Exception
Example
public class MyException extends Exception {
public MyException() {
System.out.println("User Defined Exception");
}
}
class Main {
public static void main(String args[]) {
try {
throw new MyException();
} catch (MyException m) {
System.out.println("Inside Catch Block");
}
}//User Defined Exception
} //Inside Catch Block
Predefined Exception classes
• Predefined exception classes are in the package java.lang