Exception Handling in Java
Prepared by: Shrayasi Datta
Contents
1 Introduction 2
2 Need for Exception Handling 2
3 Hierarchy of Exceptions in Java 2
4 Types of Exceptions 3
5 No Exception Handling – Program Crash 3
6 try-catch Block 3
7 Multiple Catch Blocks 4
8 Unreachable Catch Example 4
9 throw Keyword 4
10 throws Keyword 5
11 finally Block 5
12 Nested try and Multiple finally 6
13 Common Java Exceptions 6
14 Summary 7
1
Java Programming Tutorial 2
1 Introduction
Errors are common during program development. They may arise due to wrong syntax,
invalid logic, or exceptional runtime conditions. To maintain program stability, Java
provides a powerful, object-oriented mechanism called Exception Handling.
Types of Errors
• Compile-time Errors: Detected by the compiler before execution (e.g., missing
semicolons, undeclared variables, type mismatches).
• Run-time Errors: Occur during program execution (e.g., division by zero, array
index out of bounds).
• Logical Errors: The program runs but gives incorrect output due to faulty logic.
2 Need for Exception Handling
• Prevent abnormal termination of programs.
• Separate error-handling code from main logic.
• Handle unexpected situations gracefully.
• Ensure program reliability and resource cleanup.
3 Hierarchy of Exceptions in Java
All exceptions in Java are part of the [Link] package. The hierarchy begins from the
Object class, as shown below.
Explanation:
• Throwable is the superclass of all errors and exceptions.
• Error indicates serious system problems (e.g., OutOfMemoryError).
• Exception represents conditions a program can handle.
• RuntimeException and its subclasses are unchecked.
• All other exceptions are checked.
Exception Handling in Java
Java Programming Tutorial 3
4 Types of Exceptions
Built-in Exceptions:
• Checked: Must be handled or declared. Examples: IOException, SQLException,
ClassNotFoundException.
• Unchecked: Occur at runtime; not mandatory to handle. Examples: ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException.
User-defined Exceptions: Programmers can create their own by extending Exception
or RuntimeException.
5 No Exception Handling – Program Crash
// File : NoErrorHandling . java
class NoErrorHandling {
public static void main ( String [] args ) {
int a =7 , b =0;
System . out . println ( " Result is " + a / b ) ;
System . out . println ( " Program reached this line " ) ;
}
}
Output:
Exception in thread "main" [Link]: / by zero
6 try-catch Block
The try block encloses code that might throw an exception. The catch block handles
that exception.
// File : Exc2 . java
class Exc2 {
public static void main ( String args []) {
int d , a ;
try {
d = 0;
a = 42 / d ;
} catch ( A r it h m et i c Ex c e pt i o n e ) {
System . out . println ( " Division by zero . " ) ;
System . out . println ( e ) ;
}
System . out . println ( " After catch statement . " ) ;
}
}
Output:
Exception Handling in Java
Java Programming Tutorial 4
Division by zero.
[Link]: / by zero
After catch statement.
7 Multiple Catch Blocks
try {
int arr [] = new int [5];
arr [10] = 7 / 0;
}
catch ( Ar it h m et i c Ex c e pt i o n e ) {
System . out . println ( " Arithmetic Error : " + e ) ;
}
catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e ) {
System . out . println ( " Array Index Error : " + e ) ;
}
catch ( Exception e ) {
System . out . println ( " General Exception : " + e ) ;
}
Rule: More specific exceptions must appear before general ones.
8 Unreachable Catch Example
// File : SuperSubCatch . java
class SuperSubCatch {
public static void main ( String args []) {
try {
int a = 0;
int b = 42 / a ;
}
catch ( Exception e ) {
System . out . println ( " Generic Exception catch . " ) ;
}
// This causes compile error ( unreachable )
catch ( A r i th m e ti c E xc e p ti o n e ) {
System . out . println ( " Never reached . " ) ;
}
}
}
9 throw Keyword
Used to explicitly throw an exception from a method or block.
// File : W i t h E x c e p t i o n C a t c h T h r o w . java
class W it h E x c e p t i o n C a t c h T h r o w {
public static void main ( String [] args ) {
Exception Handling in Java
Java Programming Tutorial 5
int a =7 , b =0;
try {
float r = a / b ;
System . out . println ( " Result is " + r ) ;
} catch ( A r it h m et i c Ex c e pt i o n e ) {
System . out . println ( " B is zero " ) ;
throw e ; // rethrowing exception
}
System . out . println ( " Program complete " ) ;
}
}
Output:
B is zero
Exception in thread "main" [Link]: / by zero
10 throws Keyword
Used to declare an exception that a method might throw.
// File : ThrowsDemo2S . java
class ThrowsDemo2S {
static void throwOne () throws I l l e g a l A c c e s s E x c e p t i o n {
System . out . println ( " Inside throwOne . " ) ;
throw new I l l e g a l A c c e s s E x c e p t i o n ( " demo " ) ;
}
public static void main ( String args []) {
try {
throwOne () ;
} catch ( I l l e g a l A c c e s s E x c e p t i o n e ) {
System . out . println ( " Caught " + e . getMessage () ) ;
}
}
}
Output:
Inside throwOne.
Caught demo
11 finally Block
The finally block executes whether or not an exception occurs. It is ideal for cleanup
activities.
// File : Tes tFinal lyBloc k1 . java
class TestFi nallyB lock1 {
public static void main ( String [] args ) {
try {
int data = 25/0;
Exception Handling in Java
Java Programming Tutorial 6
} catch ( A r it h m et i c Ex c e pt i o n e ) {
System . out . println ( " Exception handled : " + e ) ;
} finally {
System . out . println ( " finally block executed " ) ;
}
System . out . println ( " rest of code ... " ) ;
}
}
Output:
Exception handled: [Link]: / by zero
finally block executed
rest of code...
12 Nested try and Multiple finally
// File : Tes tFinal lyBloc k3 . java
class TestFi nallyB lock3 {
public static void main ( String [] args ) {
try {
try {
int a = 100/0;
} catch ( A r i th m e ti c E xc e p ti o n e ) {
System . out . println ( " Inner catch : " + e ) ;
}
finally {
System . out . println ( " Inner finally " ) ;
}
} catch ( Exception e ) {
System . out . println ( " Outer catch : " + e ) ;
} finally {
System . out . println ( " Outer finally " ) ;
}
}
}
13 Common Java Exceptions
• ArithmeticException – divide by zero
• ArrayIndexOutOfBoundsException – invalid index
• NullPointerException – null reference
• ClassCastException – invalid type conversion
• FileNotFoundException, IOException – file I/O issues
Exception Handling in Java
Java Programming Tutorial 7
14 Summary
• Exception handling provides a robust way to handle runtime errors.
• The hierarchy begins from Throwable under [Link].
• try, catch, throw, throws, and finally form the core of this mechanism.
• Proper handling ensures smooth termination and resource management.
Exception Handling in Java