try-catch block in Java

In this article, we will discuss try-catch block in detail with explanation and example

Although, we have already encountered try-catch block in earlier articles

 

Here, we will understand the use of try-block and catch-block in depth and how exactly exception can be handled using try-catch blocks

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
  • 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)
  • try-block (i.e.; try followed by catch or try followed by finally or both) 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 stating
  • Compile-time error :-Syntax error on token “)”, Block expected after this token

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
  • This 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 stating
  • Compile-time error :-Syntax error on token “)”, Block expected after this token

Pseudo code for exception handling:

try {

	// program code that 
	// could raise or throw exception
}
catch(ExceptionType var) {

	// handle exception here
	// provide alternative solution or way
}
  • Note: you can’t keep any statement in between try-block & catch-block; otherwise compile-time error will be raised

 

A. Default Exception handling framework:

  • Before delving in depth to understand handling code for exception using try-catch block, we will re-visit default exception handling framework
  • Let us take a simple program to study default exception handling:

DefaultExceptionHandling.java

package in.bench.resources.exception.handling;

public class DefaultExceptionHandling {

	public static void main(String[] args) {

		// ArithmeticException for divide by zero
		int result = 19/0;

		// trying to print to console
		System.out.println("Result : "
				+ result);
	}
}

Output:

Exception in thread "main" java.lang.ArithmeticException:/ by zero
	at in.bench.resources.exception.handling
	.DefaultExceptionHandling
	.main(DefaultExceptionHandling.java:8)

Screen capture for above program in Eclipse IDE:

Explanation for Default exception handler:

  • Since, there are no try-catch block for above program; simply couple of line of code inside method
  • So, if any exception is raised/thrown from this method, then it is the responsibility of the method to create exception object with details such as
    1. Name of exception
    2. Description of exception
    3. Location from where exception is thrown/raised
  • Method passes over the control to JVM along with the exception object it has created
  • Now, JVM examines whether there is any exception handling-code present in the method
  • If not, then JVM terminates method abnormally and does similar checks in the caller-method for the possibility of handling code
  • If it isn’t present here also, then JVM terminates the caller-method abnormally
  • Similar checks are done by JVM till it reaches down to end of runtime stack
  • And if there are no handling code present in any of the caller-method (down in the runtime stack) then JVM passes over the control & exception object to Default Exception Handler
  • It is the duty of default exception handler to print exception information in console in the following format
 
Exception in thread “TheadName” Name-of-Exception : 
	Description-of-name 
At location (fully-qualified class name with line number
		where exception occurred Stack trace 

 

B. Exception handling using try-catch block:

  • Let us re-write same program with try-catch block

TryCatchHandler.class

package in.bench.resources.exception.handling;

public class TryCatchHandler {

	public static void main(String[] args) {

		try {

			// ArithmeticException for divide by zero
			int result = 19/0;

			// trying to print to console
			System.out.println("Result : "
					+ result);
		}
		catch(ArithmeticException aex) {

			// provide handler code here
			System.out.println("Arithmetic exception"
					+ " is caught");
		}
	}
}

Output:

Arithmetic exception is caught

Explanation:

  • When the same program is rewritten using try-catch block, the program doesn’t get terminated abnormally after raising an exception
  • Because when exception raised from try-block, then it is caught in the respective catch-block
  • Note: here, there is just one catch-block but multiple catch-blocks are possible)
  • And whatever handler-code present in the catch-block is gets executed
  • Note: there is a possibility of raising exception from catch-block also

 

Summary of try-catch block:

  • Any line of code which might raise exception during program execution should be placed inside try-block
  • Once exception raised from try-block, remaining code won’t gets executed
  • Caution: There is possibility of raising exception from catch-block too
  • Although, handling-code came to rescue when exception is raised from try-block but still method enclosing try-catch block terminates abnormally

 

References:

 

Read Also:

 

Happy Coding !!
Happy Learning !!

finally block in Java
Checked Exception v/s Unchecked Exception