Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects

Saturday, 18 May 2013

try catch in java Examples - Exception Handling in Java - Part 2/3

In our previous discussion we cam across the Basics of Exception Handling in java, we came to know what an Exeption is exactly ?, how java atmosphere handles Exceptions and we understands difference between Checked and Unchecked Exceptions.

In this particular blog we will come to know how to implement Exception Handling techniques efficiently in Java code. In java all Exception handling stuff moves around five main keywords and their combination. These keywords and their implementation in explained in the later part of this blog.

Exception Handling in Java

In java exception handling mechanism is based on following five keywords, lets see these keywords one by one in detail:

1) try
2) catch
3) finally
4) throws
5) throw

Whenever an exception is occurred in a Java program, JVM assumes that there is no sense of keeping the program running until the exception is handled or being thrown to some other piece of code to handle it. In certain situations (In case of Checked Exceptions) Java compiler force the programmer to write a handling code to deal with exceptions. For example let’s assume we are having a code that reads from an external file, JVM expects some handling code for the situation if the required file is not available at the run time. This is how Java maintains its integrity against code failure by allowing the programmer to write handling code for failure prone areas of code.

Let’s start our discussion with writing some real Exception handling code and see the real magic of handling keywords and their implementations. In java most of the handling code is being implemented using try-catch combination with a finally block added to them. By the end of this tutorial we will be able to understand functioning and implementations of event handling techniques provided by java.

How to use try-catch block in Java

Most of the time we will use try-catch block to handle exceptions of our code, and most of the exception handling stuff can be maintained using this, lets take an complete example of reading from the console. This code will read user input from the console and print the value back.
package com.beingjavaguys.core;


public class ExceptionHandling {
 public static void main(String args[]){
  BufferedReader reader = new BufferedReader(new InputStreamReader(;
  System.out.println("Enter your name : ");
  try {
   String input = reader.readLine();
   System.out.println("You typed : "+input); // Exception prone area
  } catch (IOException e) {


Enter your name :
Ankush Thakur
You typed : Ankush Thakur

Now lets discuss the above example in details and come to know more about try and catch in details.

1) try in java

A ‘try’ is the most commonly used keyword of Java Exception handling paradigm, a try block is one that is used to wrap the exception prone code inside it. In above example we are reading user’s input from the console, we have put the reading code in try catch because we don’t know if the user will type something or not, that is what handling code will do for us it will define an strategy to handle with unwanted or wrong input situation.
try {
 String input = reader.readLine(); // Exception prone area
 System.out.println("You typed : "+input);
Now in case the input is not correct or not entered, the control will goes to catch block instantly. Here the thing to note down is that if an Exeption occurs at any code line of try block, no further code in try block will be executed after that line.  Every try block must have atleast one catch or finally block with it, we will come to know about finally shortly.

2) catch in Java

This is the part of try-catch where we can write code to deal with Exception conditions or some message or a stack trace of exception object to detect the exception reasons.
catch (IOException e) {
We can have more than one catch block per try, each catch block is an exception handler that handles the type of exception that is being declared as its argument. The argument must be a class name inherited from Throwable class.
try {
  String input = reader.readLine(); // Exception prone area
   System.out.println("You typed : "+input);
  } catch (IOException e) {
  catch (Exception e) {
The advantage behind having more than one catch is that, sometimes we can not predict which exception is going to be thrown at run time, so we can provide a list of all expected exceptions in preceding catch block.

What is printStackTrace()

public void printStackTrace(); // e.printStackTrace()
The method printStackTrace() helps us to find the exact error location and name of method causing the error in our code. It is a standard way of representing errors and exceptions in Java.

In java every executing program places the details of its invoking methods onto the execution stack, along with classes and object names and the line number of the code line that is being executing. Whenever an exception is occurred printStackTrace() can be used to print the contents of the execution stack, this way the programmer gets the situation in more details and to the point.

Multiple try-catch in Java

In situation of having more than one catch block, JVM will trace an appropriate catch block from start and will execute accordingly. As soon as JVM finds exact catch, it will skip all other catch blocks.

Here one thing to note down is that we must have declared narrow exceptions first and broad one last, for example Exception class contains all exceptions in it, if we would write a catch with Exception class first JVM will use that catch and will not reach to exact IOException block.

Here one important thing to note down is that, at a time only one exception is thrown and only one catch is executed.

In next blog we will see more about exception handling in java and more about throw, throws and finally in Java.

Thanks for reading !
Being Java Guys Team


Post a Comment

Like Us on Facebook

Like Us On Google+


Skype: neel4soft