java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Exception Handling in Java: A Complete Tutorial
Last Updated on: 23rd Nov 2025 16:13:26 PM
In real-world applications, errors can happen anytime — wrong user input, network failure, file not found, division by zero, etc.
If these errors are not handled properly, the program may crash.
To prevent this, Java provides a powerful mechanism called Exception Handling.
Exception Handling allows a program to:
✔ Detect errors
✔ Handle them gracefully
✔ Continue program execution without crashing
It improves:
-
Program stability
-
Error reporting
-
User experience
-
Security
Java uses a structured model with try–catch–finally, throw, throws, and custom exceptions to handle different types of errors efficiently.
What is an Exception?
An exception is an unwanted event that occurs during program execution and disrupts the normal flow of the program.
Example:
-
Dividing a number by zero
-
Accessing an invalid array index
-
File not found
-
Null object access
Types of Errors in Java
1. Compile-time Errors
Errors detected by the compiler. Example: missing semicolon, wrong syntax.
2. Runtime Errors (Exceptions)
Errors that happen while the program is running. Example: ArithmeticException, NullPointerException.
3. Logical Errors
Program runs but produces wrong output.
Types of Exceptions in Java
Java divides exceptions into two categories:
1️⃣ Checked Exceptions
Caught by the compiler . These are checked at compile-time. Must be handled using try–catch or throws.
Examples:
-
IOException
-
SQLException
-
FileNotFoundException
2️⃣ Unchecked Exceptions
These occur at runtime and are not checked by the compiler. They usually result from programming errors. Occur due to programming mistakes
Examples:
-
ArithmeticException
-
NullPointerException
-
ArrayIndexOutOfBoundsException
Exception Hierarchy Diagram
Throwable
|
|-- Exception
| |-- RuntimeException
| |-- IOException
| |-- SQLException
|
|-- Error
|-- StackOverflowError
|-- OutOfMemoryError
Java Exception Handling Keywords
| Keyword | Meaning |
|---|---|
| try | Code that may throw an exception |
| catch | Handle the exception |
| finally | Always executes (cleanup code) |
| throw | Throw an exception manually |
| throws | Declare exception to JVM |
| custom exception | User-defined exception class |
1. try–catch Example
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
OUTPUT
Cannot divide by zero!
2. Using Multiple catch Blocks
public class Main {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("Null value found!");
} catch (Exception e) {
System.out.println("Other exception occurred.");
}
}
}
3. finally Block Example
The finally block always executes.
try {
int a = 5 / 0;
} catch (Exception e) {
System.out.println("Exception handled.");
} finally {
System.out.println("Finally block executed.");
}
4. throw Keyword Example (Manual Exception)
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied");
} else {
System.out.println("Access granted");
}
}
public static void main(String[] args) {
checkAge(15);
}
}
5. throws Keyword Example
Used when a method may throw an exception.
import java.io.*;
class Test {
void readFile() throws IOException {
FileReader fr = new FileReader("data.txt");
}
public static void main(String[] args) {
Test t = new Test();
try {
t.readFile();
} catch (IOException e) {
System.out.println("File not found!");
}
}
}
6. Custom Exception Example
class InvalidAmountException extends Exception {
InvalidAmountException(String msg) {
super(msg);
}
}
public class Bank {
void withdraw(int amount) throws InvalidAmountException {
if (amount < 0) {
throw new InvalidAmountException("Amount cannot be negative!");
} else {
System.out.println("Withdrawal successful: " + amount);
}
}
public static void main(String[] args) {
Bank b = new Bank();
try {
b.withdraw(-100);
} catch (InvalidAmountException e) {
System.out.println(e.getMessage());
}
}
}
Real-Life Example: Online Payment Failure
class PaymentFailedException extends Exception {
PaymentFailedException(String msg) {
super(msg);
}
}
class PaymentGateway {
void processPayment(boolean status) throws PaymentFailedException {
if (!status) {
throw new PaymentFailedException("Payment Failed! Try Again.");
} else {
System.out.println("Payment Successful");
}
}
}
public class Main {
public static void main(String[] args) {
PaymentGateway pg = new PaymentGateway();
try {
pg.processPayment(false);
} catch (PaymentFailedException e) {
System.out.println(e.getMessage());
}
}
}
Output
Payment Failed! Try Again.
Final Summary
-
Exception Handling avoids program crashes
-
Java provides try, catch, finally, throw, throws
-
Two types: Checked and Unchecked
-
We can create Custom Exceptions
-
Helps build robust, error-free applications
Keep practicing — you're doing amazing!
Happy Coding! ![]()
.png)