Exception Handling is one of the core concepts in Java that helps you manage runtime errors and maintain the normal flow of your program.
Java provides 5 important keywords to handle exceptions effectively:
- try
- catch
- finally
- throw
- throws
In this blog, we’ll understand each keyword with clear definitions,Uses and examples.
1. try
Definition:
- The
tryblock is used to enclose code that might throw an exception. - It must be followed by either
catchorfinally.
Uses of try:
- To wrap risky code like file operations, network calls, or arithmetic operations.
- To prevent the program from crashing by allowing exception handling.
- Works with catch or finally blocks.
Example:
try {
int result = 10 / 0;
}
2. catch
Definition:
- The
catchblock is used to handle the exception thrown in the try block.
Uses of catch:
- To handle runtime errors gracefully.
- To avoid program termination.
- Can have multiple catch blocks to handle different exceptions.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Multiple catch Example:
try {
int result = 10 / 0;
String str = null;
System.out.println(str.length());
} catch (ArithmeticException e) {
System.out.println("Math error");
} catch (NullPointerException e) {
System.out.println("Null object used");
}
3. finally
Definition:
- The
finallyblock is used to execute important code regardless of exception occurrence. - It always executes (except JVM crash).
Uses of finally:
- To release resources (files, DB connections).
- To execute mandatory cleanup code even if an exception occurs.
- Can be used without catch (optional).
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error occurred");
} finally {
System.out.println("Cleanup code");
}
4. throw
Definition:
- The
throwkeyword is used to explicitly throw an exception. - It is used when you want to manually create and throw an exception.
Syntax:
throw new ExceptionType("message");
Example:
public class Demo {
public static void main(String[] args) {
int age = 16;
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
System.out.println("Eligible to vote");
}
}
Uses of throw
1. Input Validation
if (amount < 0) {
throw new IllegalArgumentException("Amount cannot be negative");
}
2. Business Logic Validation
if (balance < withdrawAmount) {
throw new ArithmeticException("Insufficient balance");
}
3. Custom Error Handling
You can create and throw your own exceptions
throw new RuntimeException("Something went wrong");
5. throws
Definition:
- The
throwskeyword is used in a method declaration to declare exceptions that a method might throw. - It tells the caller: “Hey, this method may cause an exception — you handle it!”
Syntax:
returnType methodName() throws ExceptionType {
}
Example:
import java.io.*;
public class Demo {
public static void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("File error");
}
}
}
Uses of throws
1. Delegating Exception Handling
Instead of handling inside method, pass it to caller
public void process() throws IOException {
// risky code
}
2. Cleaner Code
Keeps method clean without try-catch
3. Required for Checked Exceptions
Compiler forces you to handle or declare
Key Differences Between throw and throws
| Feature | throw | throws |
|---|---|---|
| Purpose | Actually throws exception | Declares exception |
| Usage | Inside method/block | Method signature |
| Number | One exception at a time | Can declare multiple |
| Example | throw new Exception() | throws IOException |
| Control | Immediate | Delegates to caller |
Real-Time Example
Banking Scenario:
public class Bank {
public static void withdraw(int balance, int amount) {
if (amount > balance) {
throw new ArithmeticException("Insufficient balance");
}
System.out.println("Withdrawal successful");
}
public static void main(String[] args) {
withdraw(1000, 2000);
}
}
File Handling Scenario:
public void readData() throws IOException {
FileReader file = new FileReader("data.txt");
}
-
throw→ Used to explicitly throw an exception -
throws→ Used to declare exceptions in method -
throwis for creating errors,throwsis for passing responsibility
Both are essential for writing clean and maintainable Java code.
Quick Summary Table
| Keyword | Purpose |
|---|---|
| try | Wrap risky code |
| catch | Handle exception |
| finally | Always execute block |
| throw | Manually throw exception |
| throws | Declare exception |
Conclusion
Exception Handling keywords help you:
- Prevent program crashes
- Handle errors gracefully
- Maintain smooth execution
Mastering these 5 keywords is essential for writing robust and production-ready Java code.
Practice these concepts with real programs to become confident in exception handling!
Top comments (0)