Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java Exception Handling: Try, Catch, Finally, Throw & Throws Explained

Mastering Java Exception Handling

This guide walks you through Java’s exception handling mechanisms—try‑catch, finally, throw, and throws—with clear examples and best‑practice tips.

In the previous lesson we introduced Java exceptions and why they interrupt program flow. Handling those exceptions gracefully is essential for robust, maintainable code.

Below are the primary strategies for managing exceptions in Java:


1. Using a try…catch Block

The try…catch construct is the cornerstone of Java’s error‑handling model. Place any code that may throw an exception inside the try block, and catch specific exceptions afterward.

try {
  // code that might throw
}
catch(Exception e) {
  // handle exception
}

The catch clause is mandatory whenever a try block appears; it intercepts the exception and allows you to respond appropriately.

Example: Handling an ArithmeticException

class Main {
  public static void main(String[] args) {
    try {
      int divideByZero = 5 / 0;
      System.out.println("Rest of code in try block");
    } catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
  }
}

Output

ArithmeticException => / by zero

In this snippet, the division by zero triggers an ArithmeticException. The exception is caught, the catch block executes, and any code following the exception within the try block is skipped.

If the try block completes without throwing, the catch block is simply bypassed.


2. Leveraging the finally Block

A finally block always runs, regardless of whether an exception was thrown. It’s an ideal place for cleanup tasks—closing files, releasing resources, or logging.

Only one finally block can accompany a given try statement.

try {
  // code
}
catch (ExceptionType1 e1) {
  // handle
}
finally {
  // always executed
}

Example: finally After an Exception

class Main {
  public static void main(String[] args) {
    try {
      int divideByZero = 5 / 0;
    } catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    } finally {
      System.out.println("This is the finally block");
    }
  }
}

Output

ArithmeticException => / by zero
This is the finally block

The finally block executes after the catch block, ensuring that critical cleanup code runs even if an exception occurs.

Best practice: Use finally for any code that must run regardless of success or failure, such as closing streams or resetting shared state.


3. Explicitly Throwing Exceptions and Declaring Throws

The throw keyword allows you to raise an exception manually. When thrown, control jumps directly to the nearest matching catch block.

Example: Using throw

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("Trying to divide by 0");
  }

  public static void main(String[] args) {
    divideByZero();
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
        at Main.divideByZero(Main.java:5)
        at Main.main(Main.java:9)

The throws clause, on the other hand, declares that a method might propagate certain checked exceptions. It signals to callers that they must handle or further propagate the exception.

Example: Using throws with File I/O

import java.io.*;

class Main {
  // Declare that this method can throw IOException
  public static void findFile() throws IOException {
    File newFile = new File("test.txt");
    FileInputStream stream = new FileInputStream(newFile);
  }

  public static void main(String[] args) {
    try {
      findFile();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}

Output

java.io.FileNotFoundException: test.txt (The system cannot find the file specified)

If the file does not exist, FileInputStream throws FileNotFoundException, which is a subclass of IOException. Because findFile() declares throws IOException, the main method must handle it.

When a method does not catch an exception internally, you must declare it with throws to inform callers of the potential failure.

For deeper insight, explore Java’s throw and throws documentation.


Java

  1. Master Java Operators: Types, Syntax, & Practical Examples
  2. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  3. Java Exceptions: Types, Hierarchy & Handling
  4. Mastering Java Exception Handling: Try, Catch, Finally, and Resources
  5. Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained
  6. Creating Custom Exceptions in Java: A Step‑by‑Step Guide
  7. Understanding Java's throws Keyword: Examples & Best Practices
  8. Mastering Java Exceptions: Handling Unexpected Errors Gracefully
  9. Mastering C++ Exception Handling: A Comprehensive Guide
  10. Mastering C# Exception Handling: Strategies & Best Practices