DEV Community

Jayashree
Jayashree

Posted on

Exception Handling in Java: 5 Important Keywords (With Examples)

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 try block is used to enclose code that might throw an exception.
  • It must be followed by either catch or finally.

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;
}
Enter fullscreen mode Exit fullscreen mode

2. catch

Definition:

  • The catch block 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");
}
Enter fullscreen mode Exit fullscreen mode

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 finally block 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");
}
Enter fullscreen mode Exit fullscreen mode

4. throw

Definition:

  • The throw keyword 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");
Enter fullscreen mode Exit fullscreen mode

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");
    }
}
Enter fullscreen mode Exit fullscreen mode

Uses of throw

1. Input Validation

if (amount < 0) {
    throw new IllegalArgumentException("Amount cannot be negative");
}
Enter fullscreen mode Exit fullscreen mode

2. Business Logic Validation

if (balance < withdrawAmount) {
    throw new ArithmeticException("Insufficient balance");
}
Enter fullscreen mode Exit fullscreen mode

3. Custom Error Handling

You can create and throw your own exceptions

throw new RuntimeException("Something went wrong");
Enter fullscreen mode Exit fullscreen mode

5. throws

Definition:

  • The throws keyword 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 {
}
Enter fullscreen mode Exit fullscreen mode

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");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Uses of throws

1. Delegating Exception Handling

Instead of handling inside method, pass it to caller

public void process() throws IOException {
    // risky code
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

File Handling Scenario:

public void readData() throws IOException {
    FileReader file = new FileReader("data.txt");
}
Enter fullscreen mode Exit fullscreen mode
  • throw → Used to explicitly throw an exception
  • throws → Used to declare exceptions in method
  • throw is for creating errors, throws is 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)