Java throw and throws
What is Java throw and Throws?
In Java, throw and throws are keywords used in exception handling.
throw is used to explicitly throw an exception from a method or block of code. It is followed by an instance of the Throwable class or one of its subclasses.
throws is used in a method signature to declare that the method may throw one or more types of exceptions. This allows callers of the method to handle or propagate the exceptions appropriately.
- To understand the Java Throw and Throws, Read the Complete Article.
Java Exceptions:
- In Java, exceptions can be categorized into two types:
- Checked Exceptions: These are the exceptions that are checked by the compiler at the time of compilation. If a method throws a checked exception, the method must either handle the exception or declare it using the throws keyword. Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.
- Unchecked Exceptions: These are the exceptions that are not checked by the compiler at the time of compilation. These are also known as runtime exceptions. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException
- It’s important to note that while unchecked exceptions do not have to be declared or handled explicitly,
Let’s look at the Java Throw and Throws to perform certain operations.
Example 1: Java Program to Java throws Keyword
Run
import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a number: "); String input = reader.readLine(); int number = Integer.parseInt(input); System.out.println("The number is: " + number); } }
Output
Enter a number: 9 The number is: 9
Explanation:
In this example, the main() method declares that it may throw an IOException by using the throws keyword in its signature.
This is because the readLine() method of the BufferedReader class may throw an IOException if there is an error reading input from the user.
By declaring that main() may throw an IOException, the method is essentially stating that it will not handle the exception itself but instead will propagate it up the call stack.
we could have also handled the exception ourselves using a try-catch block instead of declaring it to be thrown.
Example 2 : Throwing multiple exceptions
Run
public class Main { public static void main(String[] args) { int age = -1; try { setAge(age); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } } public static void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } System.out.println("Age is: " + age); } }
Output
Age cannot be negative
Explanation:
In this example, we have a method called setAge() that takes an integer argument representing a person's age.
If the age is negative, the method throws an IllegalArgumentException with the message "Age cannot be negative" using the throw keyword.
In the main() method, we call setAge() with a negative value of -1. Since setAge() throws an exception, we use a try-catch block to catch the exception and print its message to the console.
When we run this program, we should see the message "Age cannot be negative" printed to the console.
Example 3 : How to use checked exceptions in Java.
import java.io.*; public class Main { public static void main(String[] args) { try { readFile("myfile.txt"); } catch (IOException ex) { System.out.println("An error occurred while reading the file: " + ex.getMessage()); } } public static void readFile(String fileName) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } }
Output
An error occurred while reading the file: myfile.txt (No such file or directory)
Explanation:
In this code, the readFile() method reads from a file named myfile.txt and prints its contents to the console. The readFile() method declares that it may throw an IOException using the throws keyword.
In the main() method, we call the readFile() method and surround it with a try-catch block. The try block contains the call to the readFile() method. If an IOException occurs during the execution of the readFile() method, it will be caught by the catch block, and an error message will be printed to the console.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment