Exception Handling in Java
Exception handling is used to handle errors in a program so that the program does not stop
suddenly.
Exception handling is a mechanism to handle runtime errors and continue program execution
normally.
Or
Exception handling helps prevent program crashes.
Example
Imagine:
You are withdrawing money from an ATM.
Suddenly network fails.
Instead of shutting down the ATM completely,
it shows:
"Transaction Failed. Try Again."
This is similar to exception handling.
The system handles the error gracefully.
What is an Exception?
An exception is an unwanted event/error that occurs during program execution.
Examples:
dividing by zero
accessing invalid array index
file not found
Example Without Exception Handling
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 0;
int c = a / b;
[Link](c);
}
}
Output
Exception in thread "main"
[Link]: / by zero
Program stops immediately.
Why Use Exception Handling?
It helps:
avoid abnormal termination
continue program execution
handle errors properly
improve user experience
Ways to Handle Exceptions in Java
Main keywords:
Keyword Purpose
try Code that may cause exception
catch Handles the exception
Keyword Purpose
finally Always executes
throw Used to manually throw exception
throws Declares exception
1. try and catch
Syntax
try {
// risky code
} catch(Exception e) {
// handling code
}
Example
public class Main {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b;
[Link](c);
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
[Link]("Program continues");
}
}
Output
Cannot divide by zero
Program continues
Step-by-Step Explanation
try Block
try {
int c = a / b;
}
Contains risky code.
catch Block
catch (ArithmeticException e)
Handles the exception.
try = check error
catch = handle error
2. finally Block
finally block always executes whether exception occurs or not.
Example
public class Main {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Exception handled");
}
finally {
[Link]("Finally block executed");
}
}
}
Output
Exception handled
Finally block executed
Real-Life Example
Think of exam:
Student may pass or fail
But school always publishes result
That is like finally.
3. throw Keyword
throw is used to manually create an exception.
Example
public class Main {
public static void main(String[] args) {
int age = 15;
if(age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
[Link]("Eligible");
}
}
Output
Exception in thread "main"
[Link]:
Not eligible to vote
Explanation
throw new ArithmeticException(...)
Manually throws exception.
Real-Life Example
Security guard checking age:
If age < 18
Entry denied
Same idea.
4. throws Keyword
throws is used to declare exceptions.
It tells:
“This method may cause exception.”
Example
import [Link].*;
class Test {
void readFile() throws IOException {
FileReader f = new FileReader("[Link]");
}
}
public class Main {
public static void main(String[] args) {
[Link]("File handling");
}
}
Explanation
throws IOException
Means:
this method may generate IOException
Difference Between throw and throws
throw throws
Used to throw exception manually Used to declare exception
Used inside method Used in method declaration
Multiple catch Example
public class Main {
public static void main(String[] args) {
try {
int arr[] = {1,2,3};
[Link](arr[5]);
} catch (ArithmeticException e) {
[Link]("Arithmetic Error");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Error");
}
}
}
Output
Array Index Error
Important Exception Types
Exception Cause
ArithmeticException Divide by zero
ArrayIndexOutOfBoundsException Wrong array index
NullPointerException Using null object
NumberFormatException Wrong number conversion
Complete Flow of Exception Handling
try → catch → finally
try checks risky code
catch handles error
finally always runs
Difference Between throw and throws in Java
Students usually get confused between throw and throws.
The easiest way to remember is:
throw → actually throws an exception
throws → only declares possibility of exception
1. throw Keyword
Meaning
throw is used to manually create and throw an exception.
Easy Definition
throw is used when we want to generate an exception ourselves.
Real-Life Example
Imagine a security guard:
If age < 18
→ Guard throws the person out
The guard is actively taking action.
Same in Java:
throw actively creates an exception.
Syntax
throw new ExceptionName("Message");
Example of throw
public class Main {
public static void main(String[] args) {
int age = 15;
if(age < 18) {
throw new ArithmeticException("Not eligible for voting");
}
[Link]("Eligible for voting");
}
}
Output
Exception in thread "main"
[Link]:
Not eligible for voting
Step-by-Step
Step 1
if(age < 18)
Condition becomes true.
Step 2
throw new ArithmeticException(...)
Exception is manually created.
Important Point
throw:
throws only one exception at a time
used inside method/block
2. throws Keyword
Meaning
throws is used to declare that:
“This method may cause an exception.”
It does not create exception.
It only gives warning/information.
Easy Definition
throws tells the compiler that a method might generate an exception.
Just giving warning.
Same:
throws only declares possibility.
Syntax
returnType methodName() throws ExceptionName
Example of throws
import [Link].*;
class Test {
void readFile() throws IOException {
FileReader f = new FileReader("[Link]");
[Link]("File opened");
}
}
public class Main {
public static void main(String[] args) {
[Link]("Program running");
}
}
Explanation
throws IOException
Means:
this method may produce IOException
Main Difference
throw throws
Used to throw exception manually Used to declare exception
Used inside method Used in method declaration
Followed by object Followed by exception class
Throws one exception Can declare multiple exceptions
Easy Memory Trick
throw = action
throws = warning
Example Showing Both Together
class Test {
void checkAge(int age) throws ArithmeticException {
if(age < 18) {
throw new ArithmeticException("Under Age");
}
else {
[Link]("Eligible");
}
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
[Link](15);
}
}
Explanation
Here:
throws ArithmeticException
declares possibility of exception.
And:
throw new ArithmeticException(...)
actually creates exception.
Real-Life Analogy Together
Situation Java
Warning board: “Slippery Floor” throws
Actually slipping and falling throw
Very Easy Final Definition for Students
throw
Used to manually create and throw an exception.
throws
Used to declare that a method may generate an exception.
class ATM {
int balance = 5000;
void withdraw(int amount) {
try {
[Link]("Current Balance = " + balance);
[Link]("Withdraw Amount = " + amount);
// Checking balance
if(amount > balance) {
throw new ArithmeticException("Insufficient Balance");
}
balance = balance - amount;
[Link]("Remaining Balance = " + balance);
} catch (ArithmeticException e) {
[Link]("Exception: " + [Link]());
}
}
}
public class Main {
public static void main(String[] args) {
ATM a = new ATM();
[Link](2000); // valid
[Link]();
[Link](6000); // exception
}
}
Output
Current Balance = 5000
Withdraw Amount = 2000
Remaining Balance = 3000
Current Balance = 3000
Withdraw Amount = 6000
Exception: Insufficient Balance
Step-by-Step Explanation
Step 1: Initial Balance
int balance = 5000;
ATM starts with ₹5000.
Step 2: Withdraw Method
void withdraw(int amount)
Method accepts withdrawal amount.
Step 3: Check Balance
if(amount > balance)
Checks if withdrawal amount is greater than balance.
Step 4: Raise Exception
throw new ArithmeticException("Insufficient Balance");
Manually creates exception.
Step 5: catch Block
catch (ArithmeticException e)
Handles the exception and displays message.
Real-Life Explanation for Students
Think of ATM:
If balance is enough → money is given
If balance is low → ATM shows:
"Insufficient Balance"
This is exactly what exception handling does.
Important Concepts Used
Concept Used
Class ATM
Method withdraw()
Exception Handling try-catch
Manual Exception throw
Condition if(amount > balance)
Simple One-Line Definition
throw is used here to manually generate an exception when balance is insufficient.