5 important keywords in Java Exception handling

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

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

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

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

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.
  • Pseudo code:
    try {
    
    	// some valid Java statements
    	throw new RuntimeException();
    }
    catch(Throwable th) {
    
    	// handle exception here
    	// or re-throw caught exception
    }
    
  • Read more about throw clause or throw keyword in detail

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 5 important keywords of Java Exception handling:

  • This program covers all important 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

 

References:

 

Happy Coding !!
Happy Learning !!

User-defined Exception or Custom Exception in Java
Exception propagation in Java