In this article, we will discuss 5 important keywords related to Java exception handling i.e.;
- try
- catch
- finally
- throw
- throws
Although we have covered every keyword individually, let us summarize each keyword with few lines and finally one example covering each keyword in a single program
1. try-block:
- The code which might raise exception must be enclosed within try-block
- try-block must be followed by either catch-block or finally-block, at the end
- If both present, it is still valid but the sequence of the try-catch-finally matters the most
- Otherwise, compile-time error will be thrown for invalid sequence
- The valid combination like try-catch block or try-catch-finally blocks must reside inside method
- Note: code inside try-block must always be wrapped inside curly braces, even if it contains just one line of code;
- Otherwise, compile-time error will be thrown
- Compile-time Error : “Syntax error on token “)”, Block expected after this token”
- Read more about try block in detail
2. catch-block:
- Contains handling code for any exception raised from corresponding try-block and it must be enclosed within catch block
- catch-block takes one argument which should be of type Throwable or one of its sub-classes i.e.; class-name followed by a variable
- Variable contains exception information for exception raised from try-block
- Note: code inside catch-block must always be wrapped inside curly braces, even if it contains just one line of code;
- Otherwise, compile-time error will be thrown
- Compile-time Error: “Syntax error on token “)”, Block expected after this token”
- Read more about catch block in detail
3. finally-block:
- finally block is used to perform clean-up activities or code clean-up like closing database connection & closing streams or file resources, etc
- finally block is always associated with try-catch block
- With finally-block, there can be 2 combinations
- One is try-block is followed by finally-block and other is try-catch-finally sequence
- The only other possible combination is try block followed by multiple catch block and one finally block at the end (this is case of multiple catch blocks)
- Advantage: The beauty of finally block is that, it is executed irrespective of whether exception is thrown or NOT (from try-block)
- Also, it gets executed whether respective exception is handled or NOT (inside catch-block)
- Note: finally block won’t get executed if JVM exits with System.exit() or due to some fatal error like code is interrupted or killed
- Read more about finally block in detail
4. throw clause:
- Sometimes, programmer can also throw/raise exception explicitly at runtime on the basis of some business condition
- To raise such exception explicitly during program execution, we need to use throw keyword
- Syntax:
- throw instanceOfThrowableType
- Generally, throw keyword is used to throw user-defined exception or custom exception
- Although, it is perfectly valid to throw pre-defined exception or already defined exception in Java like IOException, NullPointerException, ArithmeticException, InterruptedExcepting, ArrayIndexOutOfBoundsException, etc.
- Read more about throw clause or throw keyword in detail
- Pseudo code:
try {
// some valid Java statements
throw new RuntimeException();
}
catch(Throwable th) {
// handle exception here
// or re-throw caught exception
}
5. throws keyword or throws clause:
- throws keyword is used to declare the exception that might raise during program execution
- whenever exception might thrown from program, then programmer doesn’t necessarily need to handle that exception using try-catch block instead simply declare that exception using throws clause next to method signature
- But this forces or tells the caller method to handle that exception; but again caller can handle that exception using try-catch block or re-declare those exception with throws clause
- Note: use of throws clause doesn’t necessarily mean that program will terminate normally rather it is the information to the caller to handle for normal termination
- Any number of exceptions can be specified using throws clause, but they are all need to be separated by commas (,)
- throws clause is applicable for methods & constructor but strictly not applicable to classes
- It is mainly used for checked exception, as unchecked exception by default propagated back to the caller (i.e.; up in the runtime stack)
- Note: It is highly recommended to use try-catch for exception handling instead of throwing exception using throws clause
- Read more about throws clause or throws keyword in detail
Demo program on Java Exception handling:
- This demo program covers all 5 keywords related to Java Exception handling
DemoOnTryCatchFinallyThrowThrows.java
package in.bench.resources.exception.handling;
public class DemoOnTryCatchFinallyThrowThrows {
// main() method - start of JVM execution
public static void main(String[] args) {
try {
// call division() method
String welcomeMessage = welcomeMessage("SJ");
// print to console
System.out.println("The returned welcome message : "
+ welcomeMessage);
}
catch (NullPointerException npex){
System.out.println("Exception handled : "
+ npex.toString());
}
finally {
System.out.println("Rest of the clean-up code here");
}
}
// division method returning quotient
public static String welcomeMessage(String name)
throws NullPointerException {
if(name == null) {
// explicitly throwing Null Pointer Error
// using throw keyword
throw new NullPointerException(
"Invoke method with VALID name");
}
// performing String concatenation
String welcomeMsg = "Welcome " + name;
/// return concatenated string value
return welcomeMsg;
}
}
Output:
The returned welcome message : Welcome SJ
Rest of the clean-up code here
Related Articles:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!