All About Exception Handling in Java

Exception Handling in Java is just the same as it is in real life. Let's say you are driving from Princeton to New York.

1.How would you handle the case where in your car meets with an accident.
2.Can you do anything to avoid break failure.
3.Can you do anything if an earth quake occurs on your way to New York ?

These are the three kinds of situation you come across in any program.

Exception handling in Java
Exception handling in Java

So, How do we handle exceptions ? How do you program your code with good exception handling ? This is the question that comes to any one's mind who has just learned OOPS concepts in Java and is looking to learn more.

Exceptions are kind of thrown when they occur. If you catch them and and do something about it, the program continues smoothly with what it was doing. If you don't catch them, the program breaks and stops and you see red lines in the output. So, why would you not catch any exception ? Why would you allow it to break and stop a program. The reason is that there are kinds of exceptions that you are not supposed to catch. Confusing, right ? Read on....

There are two types of exceptions: Checked Exception and Unchecked Exception. In other words, Compile time Exception and Runtime Exception. Yes, I am giving the other terminology because otherwise you will tell me that you have heard of them and what they are. There is double terminology for almost everything in Java. This makes Java look difficult, when it's not. You might still be feeling that Java is difficult, but never mind; let's continue on with Exception handling, so that I can show you that Exception Handling is easy.

Checked and Unchecked Exceptions

The only two types of exceptions in Java are Checked and Unchecked. There is a class in Java called Exception, whose parent class(super class) is called Throwable. Throwable has two children, Exception and Error. Both Exceptions and Errors can be thrown literally. This is because they are children of Throwable and inherit that quality from it. We will talk about Errors later. We will continue on with Exceptions. Class Exception has a lot of children classes(subclass).

Exceptions are of two types, Checked and Unchecked Exception. So, how do you know which are checked and which are unchecked? Class Exception has a child class called Runtime Exception. All its children and their children and so on... are Unchecked Exceptions. All the brothers/sisters of Runtime Exception and their families under them are Checked Exceptions. In other words, all the children(and families under them) of Exception class, except Runtime Exception, are Checked Exceptions. They are called Checked because compiler checks for them and forces you to decide on weather you want to catch and handle it or not (allow it to break and stop your program).

Example FileNotFoundException. Unchecked exceptions should never happen if handled, so the compiler does not force you to decide on its handling. If you find an unchecked exception during testing you are supposed to fix your program so that an unchecked exception never occurs. For example, the NullPointerException is like break failure. So when you find that the break has failed during testing, go and fix it. You don't handle a break failure when it happens while running the Car. It should be fixed when found, so that it never happens upon driving.

Errors are like an earthquake; they happen due to a problem in JVM or the physical machine. If they occur, they occur. You cannot do anything about them, except report them to the JVM creator or System Administrator.

Exception Handling For Checked Exceptions, the compiler will force you to do one of the two things. Either do a try catch finally or mention the throws clause at the end of the method signature. You have to fix unchecked exceptions so that they never occur. You cannot do anything about the errors; the error will be displayed on the screen when the program fails due to a JVM problem or machine problem.



About the Author

Bharat Chhajer

I have about 10 years of working experience. I provide Java Training. My website is at javasprint.com. My Java blog is at Bharat's Java Blog

Comments

  • RE: Exception Handling should not be used for logic

    Posted by keang on 01/31/2012 03:01pm

    "Exception Handling should not be used for logic" Wrong. Exceptions should not be used for flow control, they are for exceptional conditions and handling exceptional conditions requires logic. The user entering an improperly formatted number is an exceptional condition and it is perfectly reasonable to catch and handle the NumberFormatException. If we were to follow your logic then there would be no need for exception handling at all as we would pre-check every possible condition before doing anything. Do you want to let the "current operation to fail and a stack trace to be dumped to the console" I never said I did want to do this, I was explaining why your comment "If you don't catch them, the program breaks and stops and you see red lines in the output" was wrong. The final line of my article needs to be modified from... This is still wrong: A ThreadDeath will not cause the program to stop or a message to be printed on the console. Admittedly ThreadDeath only occurs when the Thread's stop() method is called which shouldn't happen because its inherently unsafe to call it but there's code out there that does. An AssertionError is "in our hands", its thrown when an assert fails ie something we assume to be true isn't so - it's a programming error.

    Reply
  • no good

    Posted by wshcdr on 01/29/2012 12:25am

    No good, need explain it more in details

    Reply
  • Exception Handling should not be used for logic

    Posted by bharatchhajer on 01/27/2012 07:51am

    2.
    	    String  cost=Long.MAX_VALUE+"";
    	    Number n = parseNumber(cost);
    	    if(n != null)
    	    {
    	    	System.out.println("print string: "+cost);
    			System.out.println("print long: "+n.longValue());
    	    }
    	    
    	    String doubleCost = Double.MAX_VALUE+"";
    	    n = parseNumber(doubleCost);
    	    if(n != null)
    	    {
    	    	System.out.println("print string: "+doubleCost);
    		System.out.println("print double: "+n.doubleValue());
    	    }
    	
    
    	public static Number parseNumber(String str) 
    	{ 
    	  NumberFormat formatter = NumberFormat.getInstance(); 
    	  ParsePosition pos = new ParsePosition(0); 
    	  Number number = formatter.parse(str, pos);
    	  if(pos.getIndex() != 0) return number;
    	  else return null;
    	} 
    
    3.Do you want to let the "current operation to fail and a stack trace to be dumped to the console" ?
    4.The final line of my article needs to be modified from
    	"due to a JVM problem or machine problem." to
    	"due to a JVM problem or machine problem or such problems which are not in our hands"

    Reply
  • Poor and inaccurate

    Posted by keang on 01/23/2012 01:41pm

    1. The road trip description is a terrible analogy for explaining exceptions. 2. Not all unchecked exceptions require a code fix. There are times you want to catch and handle an unchecked exception such as when parsing user input string values into numbers, if the string doesn't contain a valid number you will get a NumberFormatException. This is not a coding problem that can be fixed, the code should catch the exception and notify the user. 3. Not catching thrown exceptions will not necessarily cause the program to crash and stop. For instance, uncaught Exceptions thrown on the EventThread will cause the current operation to fail and a stack trace to be dumped to the console but will not cause the program to crash and stop. 4. Not all Errors are due to a problem in the JVM or machine. For example: Errors such as AssertionError and ThreadDeath are thrown for entirely different reasons - the reason they are sub classes of Error is because in most cases you should never attempt to catch them.

    • Exception Handling should not be used for logic

      Posted by bharatchhajer on 01/27/2012 08:06am

      2.
              //Parsing a number with out catching NumberFormatException
              String doubleCost = Double.MAX_VALUE+"";
      	n = parseNumber(doubleCost);
      	if(n != null)
              {
      	   System.out.println("print string: "+doubleCost);
      	   System.out.println("print double: "+n.doubleValue());
              }
      	
      
      	public static Number parseNumber(String str) 
      	{ 
      	  NumberFormat formatter = NumberFormat.getInstance(); 
      	  ParsePosition pos = new ParsePosition(0); 
      	  Number number = formatter.parse(str, pos);
      	  if(pos.getIndex() != 0) return number;
      	  else return null;
      	} 
      
      3.Do you want to let the "current operation to fail and a stack trace to be dumped to the console" ?
      4.The final line of my article needs to be modified from
      	"due to a JVM problem or machine problem." to
      	"due to a JVM problem or machine problem or such problems which are not in our hands"

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds