EXCEPTIONS
IN JAVA
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE
1
EXCEPTION HANDLING IN
What is an Exception? JAVA
An exception is an unexpected event that occurs during the execution of a program, which
disrupts the normal flow of instructions.
Java provides a robust Exception Handling mechanism to detect and manage these events,
ensuring the program doesn't crash and can either recover or fail gracefully.
🧠🧠 Example: Dividing by zero, accessing an invalid array index, or opening a file that doesn’t exist.
What is Exception Handling?
Exception Handling is a mechanism in Java to handle runtime errors, so the normal flow of the
application can be maintained.
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 2
EXCEPTION HANDLING IN
JAVA
🎯🎯 Why is Exception Handling Important?
To catch errors instead of crashing the program.
To show user-friendly messages.
To allow the program to continue running even if something goes wrong.
Helps in troubleshooting by providing stack trace and error messages
Provides ways to recover from errors
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 3
EXCEPTION HANDLING IN
JAVA
🔧🔧 Java's 5 Main Keywords for Exception Handling
KEYWORD USE
USED FOR
try Write risky code inside this
PRE-DEFINED
EXCEPTIONS catch Write what to do if error happens
finally Block that always executes (cleanup code)
throw Manually throw an exception
COMPULSORY throws Declare that a method might throw an exception
EXECUTION
USED FOR
USER-DEFINED
EXCEPTIONS
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 4
EXCEPTION HANDLING IN JAVA
EXAMPLE:
public class Example {
public static void main(String[] args) {
try {
int a = 5 / 0; // risky code
System.out.println(a);
} catch (ArithmeticException e) {
System.out.println("You can't divide by zero!");
} finally {
System.out.println("This always runs.");
}
}
}
OUTPUT:
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 5
EXCEPTION HANDLING IN
💡💡 Real-Life Analogy:
JAVA
Try block: Trying to withdraw money from an ATM
Catch block: ATM says “Insufficient balance” if there’s not enough money
Finally block: ATM card comes out no matter what
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 6
EXCEPTION HANDLING IN
🔄🔄 Exception Hierarchy in Java
JAVA
In Java, all errors and exceptions are objects. These objects are part of the class
hierarchy that starts from the Throwable class.
The Throwable class has two main subclasses:
Exception – for errors that we can handle.
Error – for serious problems that we usually cannot handle.
java.lang.Object
java.lang.Throwable
java.lang.Exception java.lang.Error
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 7
🔄🔄 EXCEPTION HIERARCHY IN JAVA
Object
Throwable
Exception Error
→ OutOfMemoryError
Unchecked Checked → StackOverflowError
→ IOError
IOException InterruptedException
→ LinkageError
RuntimeException
→ InternalError
SQLException ClassNotFoundException
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 8
🔄🔄 EXCEPTION HIERARCHY IN
JAVA
RuntimeException IOException
→ ArithmeticException → FileNotFoundException
→ NullPointerException → EOFException
→ NumberFormatException
→ IllegalArgumentException
→ IndexOutOfBoundsException
→ ArrayIndexOutOfBoundsException
→ StringIndexOutOfBoundsException
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 9
🔄🔄 EXCEPTION HIERARCHY IN JAVA
Test.java {SOURCE CODE}
SYNTAX PROBLEMS/
Javac ERRORS PROGRAMMER’S
ERROR
Test.class
JVM EXCEPTIONS / ERRORS
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 10
🔄🔄 EXCEPTION HIERARCHY IN JAVA
EXAMPLE:
/* NullPointerException Example */
public class NullExceptionExample {
public static void main(String[] args) {
String str = null;
try {
System.out.println(str.toUpperCase());
} catch (NullPointerException e) {
System.out.println("Null Can't be Casted...");
}
}
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 11
🔄🔄 EXCEPTION HIERARCHY IN JAVA
� java.lang.Exception
These are recoverable problems.
Programmers are expected to handle them using try-catch.
Can be either:
Checked exceptions (Compile-Time Exceptions)
Unchecked exceptions (Runtime Exceptions)
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 12
🔄🔄 EXCEPTION HIERARCHY IN JAVA
✳ a. Checked Exceptions (Compile-time Exceptions)
• Handled at compile time
• Compiler forces you to use try-catch or declare with throws
• Examples:
IOException
SQLException
FileNotFoundException
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 13
🔄🔄 EXCEPTION HIERARCHY IN JAVA
import java.io.*;
public class CheckedDemo {
public static void main(String[] args) throws FileNotFoundException {
FileReader fr = new FileReader("data.txt");
}
}
import java.io.*;
public class CheckedDemo {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("data.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE
14
🔄🔄 EXCEPTION HIERARCHY IN JAVA
✳ b. Unchecked Exceptions (Runtime Exceptions)
Handled at runtime
Compiler does not force you to catch them
Occur due to logic or coding mistakes
Examples:
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 15
🔄🔄 EXCEPTION HIERARCHY IN JAVA
EXAMPLE:
public class UncheckedDemo {
public static void main(String[] args) {
int a = 10 / 0; // ArithmeticException
}
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 16
🔄🔄 EXCEPTION HIERARCHY IN JAVA
� java.lang.Error
Serious issues, not expected to be handled by programmers
Occur due to system problems (like memory overflow)
Examples:
OutOfMemoryError
StackOverflowError
VirtualMachineError
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 17
🔄🔄 EXCEPTION HIERARCHY IN JAVA
EXAMPLE:
public class ErrorDemo {
public static void recursive() {
recursive(); // StackOverflowError
}
public static void main(String[] args) {
recursive();
}
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 18
🔄🔄 EXCEPTION HIERARCHY IN JAVA
💡💡 Key Differences: Error vs Exception
FEATURE EXCEPTION ERROR
Recoverable Yes No
Handle with code? Yes (try-catch) Usually no
Examples FileNotFound, NullPointer StackOverflow, OutOfMemory
Extends Throwable Throwable
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 19
🔄🔄 EXCEPTION HIERARCHY IN JAVA
📘📘 SUMMARY
All exceptions and errors extend Throwable.
Exception is for conditions you can handle.
Error is for serious problems you cannot handle.
Checked exceptions must be handled.
Unchecked exceptions are optional to handle.
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 20
🔄🔄 EXCEPTION HANDLING IN JAVA
📘📘 EXCEPTION HANDLING KEYWORDS IN JAVA
Java provides five main keywords to handle exceptions:
try, catch, finally, throw, throws
These keywords help in writing error-free and safe programs by handling
runtime errors (exceptions) gracefully.
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 21
🔄🔄 EXCEPTION HANDLING IN JAVA
🔧🔧 1. try
Used to wrap code that might throw an exception.
This block is mandatory when using catch or finally.
If an exception occurs, control immediately shifts to the catch block.
🧠🧠 Syntax:
try {
// risky code
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 22
🔄🔄 EXCEPTION HANDLING IN JAVA
🛠🛠 2. catch
Used to handle the exception thrown in the try block.
You can use multiple catch blocks for different types of exceptions.
🧠🧠 Syntax:
try {
// risky code
} catch (ExceptionType e) {
// handling code
}
✅ Only one catch block is executed — the first one that matches the exception type.
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 23
🔄🔄 EXCEPTION HANDLING IN JAVA
EXAMPLE:
public class NumberFormatDemo {
public static void main(String[] args) {
String str = "rajganj";
try {
int a = Integer.parseInt(str);
System.out.println(a);
} catch (NumberFormatException e) {
System.out.println("String " + str + " can't be Converted to Integer");
}
System.out.println("Main Method Ended....");
}
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 24
🔄🔄 EXCEPTION HANDLING IN JAVA
🧹🧹 3. finally
This block always executes, whether an exception occurs or not.
Mainly used for cleanup actions like closing files, releasing resources, etc.
🧠🧠 Syntax:
try {
// risky code
} catch (ExceptionType e) {
// handling code
} finally {
// always executed
}
🧠🧠 Even if return is used in try or catch, finally still runs.
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 25
🔄🔄 EXCEPTION HANDLING IN JAVA
FLOWCHART: START
EXECUTE NO
TRY BLOCK
EXCEPTION
YES IGNORE
CATCH BLOCK
IGNORE THE
REST CODE OF
TRY BLOCK
EXECUTE
CATCH BLOCK
FINALLY
STOP
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 26
🔄🔄 EXCEPTION HANDLING IN JAVA
CONTROL FLOW OF try, catch AND finally:
try{
Statement 1;
Statement 2;
Statement 3;
} catch (Exception e) {
Statement 4;
} finally {
Statement 5;
}
Statement 6;
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 27
🔄🔄 EXCEPTION HANDLING IN JAVA
EXAMPLE:
public class TryCatchFnlly {
public static void main(String[] args) {
try {
System.out.println("Rajganj College");
int a=10, b=2, c;
c = a/b;
System.out.println(c);
System.out.println("Jalpaiguri");
} catch (ArithmeticException e) {
System.out.println("Can't Divide By Zero");
} finally {
System.out.println("Semester II");
}
System.out.println("DEPARTMENT OF COMPUTER SCIENCE");
}
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 28
🔄🔄 EXCEPTION HANDLING IN JAVA
🚨🚨 4. throw
Used to manually throw an exception object.
You can throw either a predefined or user-defined exception.
Only one exception can be thrown at a time.
🧠🧠 Syntax:
throw new ExceptionType (“error message”);
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 29
🔄🔄 EXCEPTION HANDLING IN JAVA
📢📢 5. throws
Used in the method signature to declare that a method might throw an
exception.
Helps pass the responsibility of handling the exception to the calling
method.
🧠🧠 Syntax:
methodName() throws ExceptionType {
//methodBody
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 30
🔄🔄 EXCEPTION HANDLING IN JAVA
EXAMPLE:
public class ThrowsDemo {
public static void main(String[] args) throws InterruptedException {
for(int i=1; i<=10; i++) {
System.out.println(i);
Thread.sleep(1000);
}
}
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 31
🔄🔄 USER-DEFINED EXCEPTION IN JAVA
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
System.out.println(msg);
}
}
public class UserDefinedException {
public static void main(String[] args) {
try {
vote(16);
} catch (Exception e) {
System.out.println(e);
}
}
public static void vote(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Not Eligible For Voting...");
} else {
System.out.println("Eligible For Voting....");
}
}
}
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 32
🔄🔄 DIFFERENCE BETWEEN THROW AND THROWS IN JAVA
FEATURE THROW THROWS
Used to declare exceptions that may
Purpose Used to manually throw an exception
occur
Position Used inside a method Used in method signature
returnType methodName() throws
Syntax throw new ExceptionType("message");
ExceptionType
Can throw only one exception at a Can declare multiple exceptions (comma-
Throws how many?
time separated)
Followed by An exception object An exception class name
throw new
Example Use void myMethod() throws IOException
ArithmeticException("Error");
Type of keyword Java statement Java declaration
Who handles it? Handled using try-catch block Handled by caller method or try-catch
Used for both checked and
Mandatory for? Mandatory for checked exceptions only
unchecked
DEPARTMENT OF COMPUTER SCIENCE, RAJGANJ COLLEGE 33