Read Also: Programs on Exception Handling in Java for Interview
According to Oracle docs
All methods throw an exception by using the throw statement. The throw statement takes a single argument: a throwable object. Throwable objects are instances(objects) of any subclass of the Throwable class.
Syntax:
throw someThrowableObject;
For Example:
throw IOException("Not able to read the stream of connected device");
Java throw keyword examples
1. Throwing an Unchecked exception
In this example, we have created the validateAge(int age) method that accepts a single integer argument age. If the age is less than 18 then we are throwing ArithmeticException otherwise printing the message You are allowed to Vote.
Note: Arithmetic Exception is considered an unchecked exception. Usually, it is not necessary to handle unchecked exceptions.
public class ThrowExampleOne { public static void main(String args[]) { validateAge(15); } public static void validateAge(int age) { if (age < 18) throw new ArithmeticException("Age is below the allowed limit"); else System.out.println(" You are allowed to Vote"); } }
Output:
Exception in thread "main" java.lang.ArithmeticException: Age is below the allowed limit
at ThrowExampleOne.validateAge(ThrowExampleOne.java:8)
at ThrowExampleOne.main(ThrowExampleOne.java:3)
2. Throwing a Checked exception
In this example, we have created the findFile() method, that throws an IOException with the message we passed to its constructor.
Note: Since IOException is a checked exception, we have to specify the throws clause.
The method that calls the findFile() method either need to handle the exception or specify it using throws keyword themselves.
import java.io.*; public class ThrowExampleTwo { public static void main(String args[]) { try { findFile(); System.out.println("Rest of the try block code"); } catch(IOException ex) { System.out.println("Inside catch block: " + ex.getMessage()); } } public static void findFile() throws IOException { throw new IOException("Not Found Any File"); } }
Output:
Inside catch block: Not Found Any File
That's all for today. Please mention in comments in case you have any questions related to throw keyword in java with examples.