understanding the 'throw' and 'throws' keywords in Java
When it comes to Java’s exception handling, throw and throws keywords demonstrate Java’s robustness in Exception Handling. Being one of the most popular programming languages, Java has it all covered. The throw and throws keywords may appear similar, but they serve very different purposes and are used in unique scenarios. With the help of this comprehensive guide, let us understand these keywords, exploring their syntax, usage, and differences, and also with some real-life examples.
To throw an exception forcefully(explicitly) in Java, we use the throw keyword. When the line containing the throw keyword is executed, it immediately stops the program and makes the other lines of code called below it unreachable. Throw keyword passes the exception to the nearest try-catch block, if it is present or just stops the execution of the program throwing the Exception mentioned in the syntax. The two ways by which we can explicitly throw an exception are,
- ‘throw new ‘Exception Name’ ();’
2. ‘throw new ‘Exception Name’ (“User Specified Error Message”);’
Our problem statement is to validate if a person is eligible to vote based on their age. If the age is less than 18, we should throw an exception indicating that the person is not eligible to vote. If the age is 18 or above, we should give a message saying that this person is Eligible to vote.
- After creating a class and its main method, we can create another method (VotingAgeCheck(int age)), that checks the condition for age and calls it in the main method.
- In the ‘VotingAgeCheck(int age)’ method, using the if block we check if the age is less than 18 and throw ‘IllegalArgumentException’ with a message saying “You should be 18 or above to vote.” if the entered age is less than 18.
- ‘IllegalArgumentException’ is a common exception in Java that indicates that a method has been passed an inappropriate or not desired argument or parameter.
- In the else block, we give out a message saying, “Eligible to vote”. The else block is executed if the if block fails, which means the entered age is 18 or more than 18.
package core_java;
public class Throw_Throws {
public static void VotingAgeCheck(int age) {
if (age < 18) {
throw new IllegalArgumentException("You should be 18 or above to vote.");
} else {
System.out.println("Eligible to vote.");
}
}
public static void main(String[] args) {
VotingAgeCheck(17);
}
}
- If we are handling the exception using try and catch, the program should be written as follows.
- We call the ‘VotingAgeCheck(17);’ method by passing its parameter in the main method within the try block to catch any exception thrown by that method.
- In the catch block, we handle ‘IllegalArgumentException’ and pass a message to the console by the ‘getMessage()’ method of the ‘Throwable’ class.
public static void main(String[] args) {
try {
VotingAgeCheck(17);
} catch (IllegalArgumentException illegalArgs) {
System.out.println(illegalArgs.getMessage());
}
}
The throws keyword in Java is used in the method signature before the method body starts. We use the throws keyword to declare that this method can throw one or more exceptions. This gives the person who is calling that method, an indication that they should handle these exceptions, either by using a try and catch block or using the throws keyword again in the method that is calling a method, which is prone to throw exceptions. The syntax for the throws keyword can be said in the way as follows.
(return type) (Method Name) (parameter) throws ExceptionName{
}
Our problem statement is to create a timer in the output console of our IDE for 6 seconds using the ‘sleep(long millis) throws InterruptedException’ method of the ‘Thread’ class.
- After creating a class and its main method, we can create another method (timer(int sec)), and create a loop that starts from 6 and ends at 0.
- Since the ‘sleep(long millis)’ method can throw ‘InterruptedException’, we mention it in the ‘timer(int sec)’ method’s signature.
- We call the ‘timer(int sec)’ method in the try block inside the main method and add a catch block to catch and handle ‘InterruptedException’ if it might occur.
- Since the sleep time is 1000 milliseconds, the execution of every iteration of the for loop is delayed by 1 second(1000 milliseconds).
package core_java;
public class Throw_Throws_2 {
public static void timer(int sec) throws InterruptedException {
for (int i = sec; i >= 0; i--) {
System.out.println("Time remaining = " + i + " seconds");
Thread.sleep(1000);
}
System.out.println("Time is up!");
}
public static void main(String[] args) {
try {
timer(6);
} catch (InterruptedException ie) {
System.out.println("The countdown was interrupted.");
}
}
- If we are not handling the exception at this stage, we can use the throws keyword again in the main method to propagate the indication of the exception to be handled at a further stage.
- This can be done by using the throws keyword at the main method’s signature along with the exception name.
package core_java;
public class Throw_Throws_2 {
public static void timer(int sec) throws InterruptedException {
for (int i = sec; i >= 0; i--) {
System.out.println("Time remaining = " + i + " seconds");
Thread.sleep(1000);
}
System.out.println("Time is up!");
}
public static void main(String[] args) throws InterruptedException {
timer(6);
}
}
Throw keyword | Throws keyword | |
Purpose | Used to explicitly throw an exception from a method or block of code. | Used in the method signature to declare that a method can throw one or more exceptions. |
How to write it? | Throw keyword is followed by the exception name. | Throws keyword is followed by one or more exceptions. |
Where to write it? | Inside a method or a block of code. | In the method declaration(signature). |
Handling | The thrown exception must be handled by the calling method using try and catch or the program execution will come to a halt. | The thrown exception must be handled by the calling method using try and catch or by propagating it using the throws keyword again in the calling method. |
- Use Descriptive Exception Messages when throwing exceptions to help with debugging and understanding the error.
- Create Custom Exceptions When Necessary for specific error conditions in the program by creating custom exception classes that extends the ‘Exception’ class.
- Catch Specific Exceptions instead of generic Exceptions to provide more targeted error handling.
- Document Exceptions in the Method Signature to indicate the exceptions thrown by a method, making your code easier to understand and maintain.
- Handle Exceptions Appropriately to maintain robustness and prevent program crashes.
It is essential to understand the throw and the throws keywords for effective error and exception handling in Java. The throw keyword allows you to explicitly throw exceptions, for specific error conditions. The throws keyword, on the other hand, is used to declare that a method can throw certain exceptions, informing the person who is calling the method to handle them. Remember to practice, stay updated with the latest trends in Automation Software Testing Course, and maintain a positive attitude throughout your interview process. With a clear understanding of these keywords and their usage in practical scenarios, we can write robust, maintainable, and reliable Java programs.
Also read: