Java Exception Handling Tutorial-2

1:38 AM 34 Comments A+ a-

Advanced Exception Handling in Java Tutorial with Example Programs

This post is in continuation of the previous Java Exception Handling Tutorial. After reading the previous post, the basic concept of using try and catch block should be clear. The other thing that is to be noted in context of using try and catch block is that try block can not exist alone, it must be followed by at least one catch block or finally block. The next step that you should learn about is the nesting of try blocks.

Nesting Try Blocks

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.
Below example program demonstates how the nesting of try blocks work in Java exception handling.

Program to demonstate nesting of try blocks in Java Exception Handling

import java.util.*;
class DemoExceptionHandling2{
 public static void main(String [] args){
  Scanner s = new Scanner(System.in);
  int a = 1;
  int b = 1;
  int n = 0;
  int c[] = {1};
  //enter value of B as zero to cause a divide by zero exception in Outer try block
  System.out.println("Enter value of B:");
  b=s.nextInt();
  //Outer Try Block
  try{
   System.out.println("Outer Try Block Entered!");
   System.out.println("A/B="+a/b);  //divide by zero exception occurs here if b=0
   System.out.println("No Exception has occured in Outer try block!!");
   //Inner Try Block
   try{
    System.out.println("Nested Try Block Entered!");
    System.out.println("Enter 0 to run normal, 1 or greater to cause ArrayIndexOutOfBoundsException:");
    n = s.nextInt();
    System.out.println("C= "+c[n]);
    System.out.println("Enter value of B again:"); //enter zero to cause divide by zero Arithmetic Exception
    b = s.nextInt();
    System.out.println("a/b ="+a/b);
    System.out.println("No exception in inner try block has occured!!");
   }
   //inner catch block will only catch Array Index Out of Bounds Exceptions
   catch(ArrayIndexOutOfBoundsException e){
    System.out.println("Exception caught in Inner catch block : "+e);
   }

  }
  //This outer catch block will catch Arithmetic Exceptions
  catch(ArithmeticException ae){
   System.out.println("Exception Caught in Outer Catch Block 1: "+ae);
  }
  //This outer catch block will catch all the uncaught Exceptions
  catch(Exception eo){
   System.out.println("Exception Caught in Outer Block 2: "+eo);
  }
  //finally block will execute every time
  finally{
   System.out.println("The code inside the finally block is executing...");
  }
  System.out.println("Line after try-catch-finally Block!");
 }
}
The above program simply demonstrates the concept of nesting try blocks in Java. I encourage you to try it yourself by adjusting the different values and notice how and which exception is being caught where. But anyway, I would like to brief the results of the above program. When you make b=0, the exception in outer try block occurs and then the whole try block including the nested inner block is skipped and the exception is caught by first catch block (which is coded to catch ArithmeticException such as divide by zero) and then the finally block is executed followed by any code afterwards. But when you make b=1, outer try block works fine and inner try block is reached. If you make n>1, then it causes ArrayIndexOutOfBoundsException to occur, which is caught by the inner catch block. But if ArrayIndexOutOfBoundsException is not caused but a Divide by Zero exception in inner try block, then there is no corresponding catch block to catch that ArithmeticException and in that case that exception is caught in the outer catch block.

Difference between throw and throws

throw: throw keyword is used to explicitly throw any exception in your java program, till now all the exceptions that were caught by the catch block, were thrown by the Java run-time system. The general form of using throw keyword is:
throw ThrowableInstance;
Here the ThrowableInstance is an object of Throwable class or any of its subclasses. Let me remind you that Throwable is the base class of Exception class, which in turn is the base class of all the exceptions. One can use the new keyword to create the object of Throwable class.

throw new IllegalAccessException;
or
throw new IllegalAccessException("demo exception");

The above two options of throwing occurs due to the presence of at least two constructors of Throwable and all of its sub-classes. One without the parameter and one with string parameter describing that exception.
throws: throws is used with methods to signal that the method might cause some exception (s) that it is not equipped to handle, so that the calling method can do the exception handling arrangements while calling that function. If a method is capable of causing an exception that it does not handle, then it must specify the type of exceptions it can cause using throws keyword followed by the comma separated list of all the exception classes that it is suspected to cause. Any method that calls such method with throws declaration must provide means of handling all those exceptions by either enclosing the function call in try-catch-finally block or rethrowing those exceptions to its calling methods, if any.
The general form of using throws is like:
type method-name(parameter-list) throws exception-list
for example:
double anyMethod(double x, double y) throws IOException, FileNotFoundException, IllegalAccessException{//method-body}

Defining and Using your own Exceptions

Java also enables you to create your own exceptions to handle situations specific to your applications. Although most of the errors are handled by Java's built-in exceptions, but being able to create your own exceptions might come handly in some particular situations depending on your application. Creating your own Exceptions is very easy, you just need to define a subclass of Exception class and specify the constructors and the other methods you want to add to specify your particular exception scenario. This new built class does not inherit any functions from Exception class as Exception class does not even define any methods of its own; it inherits from Throwable class.
Below is the simple example to demonstate how to define your own exceptions in java.
class MyException extends Exception{
 private int i;
 MyException(int x){
  i=x;
 }
}
public class MyCustomException{
 static void displayNumber(int x) throws MyException{
  System.out.println("called displayNumber("+x+")");
  if(x>15)
  {
   throw new MyException(x);
  }
  System.out.println("MyException did not occur!");
 }
  public static void main(String args[]){
   try{
    displayNumber(5);
    displayNumber(25);
   }catch(MyException me){
    System.out.println("MyException Caught: "+me);
   }
  }
 }
Exceptions handling in java is a great tool which you can handle to ensure the smooth and uninterrupted execution of your program. The above tutorials are still the basic level tutorials meant for beginners in Java only. Once you get over with these, you can try more advanced use of the Exceptions Handling in java.
If you have any questions regarding this and the previous tutorials, you can write in the comments below.

Currently working at Symantec in Chennai. Previously worked as a Senior Software Engineer at IGATE. Loves to explore new things, loves to code and solve challenging problems with the help of it. Like any other normal person, loves to watch movies, listen to songs (specially when travelling, it is must), getting to know people, travelling and whatever makes me feel good!

34 comments

Write comments
Neeta
AUTHOR
March 24, 2013 at 6:27 PM delete

thanks for the tutorial, very well explained.

Reply
avatar
Rahul Kumar
AUTHOR
March 28, 2014 at 3:45 PM delete

Great work you have done here. Thanks for posting this valuable information about Java. Webvirtue is the best Java development company in India.

Reply
avatar
November 1, 2014 at 1:06 PM delete

Earn from Ur Website or Blog thr PayOffers.in!

Hello,

Nice to e-meet you. A very warm greetings from PayOffers Publisher Team.

I am Sanaya Publisher Development Manager @ PayOffers Publisher Team.

I would like to introduce you and invite you to our platform, PayOffers.in which is one of the fastest growing Indian Publisher Network.

If you're looking for an excellent way to convert your Website / Blog visitors into revenue-generating customers, join the PayOffers.in Publisher Network today!


Why to join in PayOffers.in Indian Publisher Network?

* Highest payout Indian Lead, Sale, CPA, CPS, CPI Offers.
* Only Publisher Network pays Weekly to Publishers.
* Weekly payments trough Direct Bank Deposit,Paypal.com & Checks.
* Referral payouts.
* Best chance to make extra money from your website.

Join PayOffers.in and earn extra money from your Website / Blog

http://www.payoffers.in/affiliate_regi.aspx

If you have any questions in your mind please let us know and you can connect us on the mentioned email ID info@payoffers.in

I’m looking forward to helping you generate record-breaking profits!

Thanks for your time, hope to hear from you soon,
The team at PayOffers.in

Reply
avatar
vignesh m
AUTHOR
December 6, 2014 at 12:23 PM delete

hai,i have learned for lot infortmation...i found like that for your information.Thanks for that...hadoop training chennai
&
hadoop training chennai
&
hadoop training chennai

Reply
avatar
August 19, 2015 at 6:25 PM delete

Hi, Great tutorial.You sharing for this information very helpful for by jobs.

Manpower Consultancy in Chennai

Reply
avatar
Ace Mary
AUTHOR
October 14, 2015 at 6:31 PM delete

thanks for your efforts it is really appreciated.this is the best site i have ever seen. very clear explanation. please upload the frameworks also.then it will be very helpful to us.
PHP Training in Chennai

Reply
avatar
Abina Ragav
AUTHOR
February 12, 2016 at 7:56 PM delete

Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us.
... iOS Training in chennai

Reply
avatar
February 17, 2016 at 5:58 PM delete

Thanks for sharing such a great information..Its really nice and informative.
cloud computing training in Chennai

Reply
avatar
ravi
AUTHOR
March 5, 2016 at 4:07 PM delete

This java coding is useful and is used to helpful to improve my knowledge in order to basics.
Java Training in Chennai

Reply
avatar
Geetha Priya
AUTHOR
March 7, 2016 at 9:05 AM delete

This blog is informative. gained knowledge about new concepts and techniques Manual Testing Training in Chennai

Reply
avatar
Rekhila
AUTHOR
March 7, 2016 at 12:50 PM delete

Amazing..Clearly explained about Java Exception handing.Its very useful and informative. Program about nesting also is very clear.Thanks for sharing.
Android Training in Chennai

Reply
avatar
Giri Mani
AUTHOR
March 7, 2016 at 3:45 PM delete

in java exception handling is more important. all the exceptions are handled and with nesting try blocks. Then only the we can reduce the exception and run the function successfully.
Informatica Training in Chennai

Reply
avatar
March 7, 2016 at 3:46 PM delete

awesome article!it was nice post.in java programming language,different kind of coding formats are expressed there.in their coding some exceptions are handled by us such as throw try catch it was clearly explained in this blog.thanks for sharing this kind of valuable information.CCNA Training in Chennai

Reply
avatar
jayashree
AUTHOR
March 7, 2016 at 6:11 PM delete

I am learning java , it is really useful for me thanks for sharing this concept , it is informative.


dot net training in chennai

Reply
avatar
Geethapriya
AUTHOR
March 14, 2016 at 4:52 PM delete

This blog clearly explains the java exception concept. It will be helpful for the job seekers to build their career. Thanks for posting this information
ssrs training in chennai

Reply
avatar
rekhila
AUTHOR
March 14, 2016 at 5:02 PM delete

Clearly explained about java exception concept..Its very useful and informative to know about this java concept..Keep on sharing more blog like this..
Linux training in chennai

Reply
avatar
March 14, 2016 at 5:56 PM delete

very useful informative blog. This blog provides the advanced information of exception handling and that gives detailed explanation with examples. Thank you for this information and keep blogging like this.
VMWare Workstation Training in Chennai

Reply
avatar
swarupa
AUTHOR
March 15, 2016 at 12:25 PM delete

Java is a excellent programming language.It is used to get how to use the exception handling in java and is amazing information.
Sharepoint developer training in chennai

Reply
avatar
Maha R
AUTHOR
March 22, 2016 at 1:00 PM delete

thanks for sharing about java exception handling and nesting try blocks. its really very useful for us. keep sharing more updates.
Data warehousing Training in Chennai

Reply
avatar
rekhila
AUTHOR
March 22, 2016 at 2:12 PM delete

Amazing..Clearly explained about Java Exception handing.Its very useful and informative. Program about nesting also is very clear.Thanks for sharing...
weblogic training in chennai

Reply
avatar
Jhonathan
AUTHOR
May 20, 2016 at 1:11 PM delete

Hi harish,
This tutorial really helped me to learn about java exception handling. It was very clear to understand, thanks for blogging.
Regards,

JAVA Training in Chennai|Best JAVA Training in Chennai

Reply
avatar
Chinni Bocha
AUTHOR
May 24, 2016 at 12:07 PM delete

nice code in java..
SEO training in hyderabad by experts in digital markeing And by prosessional experts in seo.All the training by placement and also guide by the professionals.Best SEO training in hyderabad

Reply
avatar
Jhonathan
AUTHOR
May 25, 2016 at 6:57 PM delete

I really enjoyed while reading your article, the information you have delivered in this post was damn good. Keep sharing your post with efficient news.
Regards,
Hadoop Training in Chennai|Big Data Training in Chennai

Reply
avatar
Rasool Bevi
AUTHOR
June 1, 2016 at 5:50 PM delete

This Tutorial taught me more about Java Exception handling, Thanks for Sharing...
Regards,
JAVA Training in Chennai|JAVA Course in Chennai

Reply
avatar
Regina Rj
AUTHOR
June 16, 2016 at 5:49 PM delete This comment has been removed by a blog administrator.
avatar
Rakesh S
AUTHOR
June 24, 2016 at 3:41 PM delete

Thjanklu for sharig this excellent posts..
Informatica training, in the recent times has acquired a wide scope of popularity amongst the youngsters at the forefront of their career.
Informatica online training in hyderabad


Reply
avatar
Rakesh S
AUTHOR
August 12, 2016 at 1:17 PM delete


Hadoop online training .All the basic and get the full knowledge of hadoop.
hadoop online training

Reply
avatar