Professional Documents
Culture Documents
Exception Handling in Java
Exception Handling in Java
Exception
Abnormal condition
Abrupt termination
Is the message user friendly?
Definition of method 1
No exception handling
r
ro
mechanism
er
main method
e
m
n-ti
ru
If
Abrupt termination
Call to method1
Rest of the code will Definition of method 1
not execute
Exception handling
Call to method2 mechanism present
Why is it required?
Error is irrecoverable
• OutOfMemoryError
• VirtualMachineError
• AssertionError etc.
Exception - can handle such conditions and take
necessary corrective actions.
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException etc.
Throwable: Base class of Exceptions
• Exception (sub-class) • Error (sub-class)
– IOException – StackOverflowError
– SQLException – VirtualMachineError
– ClassNotFoundException – OutOfMemoryError
– RunTimeException
• ArithmeticException
• NullPointerException
• NumberFormatException
• IndexOutOfBoundsException
Types of Exceptions in Java
1. Checked Exceptions
a. Which directly inherit Throwable class
b. Checked at compile-time
c. Example: FileReader class – file specified in constructor does
not exist, FileNotFoundException occurs. Compiler prompts
the programmer to handle it.
2. Unchecked Exceptions
a. Which inherit RunTimeException class
b. Checked at run-time
c. Example: Declaring an array of 5 elements and trying to
access 6th element, ArrayIndexOutOfBoundsException
exception occurs. With method documentation, programmer
can take preventive action in code.
Exception Handling in Java
}catch(ArrayIndexOutOfBoundsException b)
{
System.out.println("Array index accessed outside the fixed size");
}
int num = 0, deno = 0;
System.out.println("enter numerator and denominator");
try
{
Scanner s1 = new Scanner (System.in);
Scanner s2 = new Scanner (System.in);
num = s1.nextInt();
deno = s2.nextInt();
try
catch
throw
throws
finally
throw keyword: Throwing exceptions
public class ExceptionClass
{
static void Check(int num)
{
if(num == zero)
throw new ArithmeticException("not valid");
else
//code here
}
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
Exception propagation Definition of method 1
method 2 called
Call to method 1
Definition of method 2
//normal execution
continues Exception occurs
Exception handling
Call to method 3 mechanism ABSENT here
throws keyword
To declare an exception
• For programmer to know about the possible exception
thrown
Checked exceptions can be forwarded in call stack