Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java throws And throw: Declaring And Throwing Exceptions

In Java, exceptions are events that can occur during the execution of a program, which can disrupt its normal flow. Java provides a robust mechanism to handle exceptions using try, catch, finally, throw, and throws keywords. In this tutorial, we will focus on the throws and throw keywords.

  • throws keyword:

The throws keyword is used in the method signature to declare that a method might throw one or more exceptions during its execution. When a method specifies exceptions using throws, the calling method must either handle these exceptions using a try-catch block or declare them using throws as well.

Example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileProcessor {
    public static void main(String[] args) {
        try {
            readFile("file.txt");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static void readFile(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String line = reader.readLine();
        System.out.println("First line: " + line);
        reader.close();
    }
}
  • throw keyword:

The throw keyword is used to explicitly throw an exception from a method or a constructor. You can throw an exception when a specific condition occurs, and you want to indicate that an error has occurred. When an exception is thrown, the normal flow of the program is interrupted, and the runtime system attempts to find an appropriate exception handler (a catch block) to deal with the exception.

Example:

public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        if (initialBalance < 0) {
            throw new IllegalArgumentException("Initial balance cannot be negative");
        }
        this.balance = initialBalance;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            throw new IllegalArgumentException("Insufficient balance");
        }
        balance -= amount;
    }

    public static void main(String[] args) {
        try {
            BankAccount account = new BankAccount(-100);
        } catch (IllegalArgumentException e) {
            System.err.println("Error: " + e.getMessage());
        }

        BankAccount account = new BankAccount(100);
        try {
            account.withdraw(200);
        } catch (IllegalArgumentException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

In conclusion, the throws keyword is used to declare exceptions that a method might throw, and the throw keyword is used to explicitly throw an exception from a method or constructor. By using these keywords, you can create more robust and fault-tolerant programs that can handle exceptions gracefully and provide meaningful error messages to users.

  1. Declaring exceptions with throws in Java: The throws clause in a method signature is used to declare that the method may throw certain exceptions.

    public void myMethod() throws IOException, SQLException {
        // method implementation
    }
    
  2. Throwing exceptions in Java with throw: The throw keyword is used to explicitly throw an exception in a method.

    public void myMethod() {
        if (someCondition) {
            throw new MyException("Custom error message");
        }
    }
    
  3. Handling exceptions with try-catch blocks in Java: Exceptions can be handled using try, catch, and optionally finally blocks.

    try {
        // code that may throw an exception
    } catch (ExceptionType e) {
        // handle the exception
    } finally {
        // optional: code that always executes
    }
    
  4. Custom exceptions and throw in Java: Custom exceptions can be created by extending Exception or its subclasses.

    public class MyException extends Exception {
        // constructor and additional methods
    }
    
  5. Java method signature with throws clause: The throws clause is part of the method signature and specifies the exceptions that the method may throw.

    public void myMethod() throws IOException, SQLException {
        // method implementation
    }
    
  6. Re-throwing exceptions in Java: Exceptions can be re-thrown to propagate them up the call stack.

    public void myMethod() throws IOException {
        try {
            // code that may throw IOException
        } catch (IOException e) {
            // handle or modify the exception
            throw e; // re-throw the exception
        }
    }
    
  7. Java throws and checked exceptions handling: Checked exceptions must be either caught using try-catch or declared in the method signature using throws.

    public void myMethod() throws IOException {
        // code that may throw IOException
    }
    
  8. Propagating exceptions up the call stack in Java: Exceptions can be propagated up the call stack by declaring them with throws and allowing higher-level methods to handle or propagate further.

    public void higherLevelMethod() throws IOException {
        lowerLevelMethod();
    }
    
    public void lowerLevelMethod() throws IOException {
        // code that may throw IOException
    }
    
  9. Throwing multiple exceptions in a method in Java: A method can throw multiple exceptions by listing them in the throws clause.

    public void myMethod() throws IOException, SQLException {
        // method implementation
    }
    
  10. Using finally block with throws and throw in Java: The finally block is used for code that needs to be executed whether an exception occurs or not.

    try {
        // code that may throw an exception
    } catch (ExceptionType e) {
        // handle the exception
    } finally {
        // code that always executes
    }