Throw and Throws Keywords in Java


In Java, exceptions are used to handle abnormal situations that can occur during the execution of a program. The throw and throws keywords are used for throwing exceptions explicitly. They allow you to control exception handling in your programs. Let's explore both keywords in detail.

1. The throw Keyword

The throw keyword is used to throw an exception explicitly in Java. It allows you to create your own exceptions and throw them from a method or a block of code. Once an exception is thrown, the flow of control is transferred to the nearest catch block, or the program terminates if there is no catch block.

Syntax of throw Keyword

    throw new ExceptionType("Error message");
        

Example of Using throw

In this example, we use the throw keyword to throw an exception manually when a value is negative.

    public class Main {
        public static void main(String[] args) {
            try {
                checkNumber(-5);  // Passing a negative number
            } catch (IllegalArgumentException e) {
                System.out.println("Caught exception: " + e.getMessage());
            }
        }
    
        static void checkNumber(int number) {
            if (number < 0) {
                throw new IllegalArgumentException("Number cannot be negative");
            } else {
                System.out.println("Number is positive");
            }
        }
    }
        

Output:

    Caught exception: Number cannot be negative
        

Explanation:

  • The checkNumber method checks if the passed number is negative.
  • If the number is negative, it throws an IllegalArgumentException using the throw keyword.
  • The exception is caught in the catch block and the error message is printed.

2. The throws Keyword

The throws keyword is used to declare exceptions that a method may throw. This allows you to specify which exceptions the method is capable of throwing without having to handle them in the method itself. It is used in the method signature.

Syntax of throws Keyword

    returnType methodName() throws ExceptionType1, ExceptionType2 {
        // method implementation
    }
        

Example of Using throws

In this example, we use the throws keyword to declare that a method may throw an IOException exception.

    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            try {
                readFile();  // Calling a method that throws an exception
            } catch (IOException e) {
                System.out.println("Caught exception: " + e.getMessage());
            }
        }
    
        static void readFile() throws IOException {
            throw new IOException("File not found");
        }
    }
        

Output:

    Caught exception: File not found
        

Explanation:

  • The readFile method is declared to throw an IOException using the throws keyword.
  • Inside the method, an IOException is thrown manually using the throw keyword.
  • The exception is caught in the catch block of the main method, and the error message is printed.

3. Difference Between throw and throws

Both throw and throws are related to exceptions, but they are used in different contexts:

  • throw is used to explicitly throw an exception from a method or a block of code.
  • throws is used in a method declaration to specify the exceptions that the method may throw during execution.

4. Example of Combining throw and throws

In this example, we combine both throw and throws keywords. The main method calls a method that may throw an exception, and the main method itself declares that it may throw an exception using the throws keyword.

    public class Main {
        public static void main(String[] args) throws Exception {
            try {
                processData(-10);  // Calling a method that throws an exception
            } catch (IllegalArgumentException e) {
                System.out.println("Caught exception: " + e.getMessage());
            }
        }
    
        static void processData(int number) throws IllegalArgumentException {
            if (number < 0) {
                throw new IllegalArgumentException("Number cannot be negative");
            }
            System.out.println("Processing number: " + number);
        }
    }
        

Output:

    Caught exception: Number cannot be negative
        

Explanation:

  • The processData method checks if the passed number is negative and throws an IllegalArgumentException using the throw keyword.
  • The main method calls processData and declares that it may throw an exception using the throws keyword.
  • The exception is caught in the catch block and the error message is printed.

5. Conclusion

The throw and throws keywords are essential tools for exception handling in Java. The throw keyword allows you to throw an exception explicitly, while the throws keyword is used to declare exceptions that a method can throw. Understanding these keywords is crucial for creating robust and error-resistant Java programs that can handle unexpected situations gracefully.





Advertisement