Java has many wonderful things and exception handling is one among them. Exception handling is a framework provided by Java to ensure program execution continues in an unfavorable problem condition by handling it gracefully. Exception handling is not new to Java guys and I need not give a heroic introduction to it. This is my attempt at writing a detailed tutorial like a chapter in a Java book, by giving comprehensive coverage to this topic accompanied by code examples, images, bells and whistles. I will give a simple and easy to understand narrative to java exception handling and try to uncover intricate detail as much as possible in my own style. As exception handling is a large topic, this will be a multi-part series.
I chose to use the word problem instead of error in the above definition. Error is a java class and given a specific meaning in Java exception handling and I didn’t want that to be mixed with the general English word which denotes an unfavorable condition. Google says, problem is “A matter or situation regarded as unwelcome or harmful and needing to be dealt with and overcome”. In general software terms we use error to signify that and they are of two types, compile time and run time. In exception handling we will be dealing only with run-time problems. In any software program, there are numerous possibilities that a problem can occur at run-time during the flow of execution. How it is handled is crucial to the business and user. Right from Ada to C++ to PHP exception handling is available.
Imagine if there is no exception handling mechanism available and what would happen if a run time error occurs. Most likely the program may crash in ugly manner resulting in an un wanted situation. In those situations, we can analyze the programs and use if-condition construct and try to salvage the situation. Repair the code and re-run it. Some problems cannot be handled and will result in reporting error code and abruptly discontinue the execution. All these will result in unorganized / non maintainable code. With Java’s exception handling mechanism we have an organized and simplified more importantly object oriented way of handling run-time problems.
At low level an exception is a java object with attributes and methods. When a problem occurs, an exception object is created, thrown and then handled.
As shown in above figure, exception handling can be grouped into these four phases. When a problem occurs it is the start of exception handling flow. A problem can be broadly classified into two. First one is, it can be handled and execution can continue, the second one is an unrecoverable serious situation which cannot be handled. An example for recoverable problem is, code block is expecting a value in a variable and it is not present. This can be handled by substituting a default value and the execution can continue. An easy example for unrecoverable condition is a hardware failure.
Java’s exception handling mechanism is object oriented. We have Throwable as the base class and all exceptions are sub classes of Throwable. We have Error and Exception as two immediate sub classes of Throwable.
Exception handling should be used judiciously. Earlier I wrote about fail fast vs fail safe and that article loosely relates to this context and my personal preference is to fail fast. Exception handling does not mean that we should take the program flow in an alternate direction than the intended one and which may cause issues in future. We should be cautious when we say handling, as in the name of handling, an issue should not be carried over to a different context of the program as it will come back to haunt us.
So when do we use exception handling, it is when we foresee that a problem may occur at run time and we know a possible solution to it at design time itself. Then at run time if that solution path is chosen it should not alter the core objective of the program. Cases like, just logging the problem and proceeding with the flow does not fit into exception handling. A popular mistake done by java developers is to use exception handling for flow control. Though we have if-else and other options, we tend to fall on exception handling side and use it as flow control mechanism which is poor.
Exceptions can be thrown by either java run time environment or by the code itself. JRE throws exception when java’s rules are violated. An example is, when the code accesses an array location which is not available then ArrayIndexOutOfBoundsException is thrown. Pretty nice name right and obviously it explains the problem. All the java exception classes are not having any attributes and standard methods. It is a common design. Class name describes what exception it is and the hierarchy forms an organization chart kind of structure using which java exceptions are used.
Programmers can throw an exception to indicate a problem condition. Either java’s predefined exceptions can be used or custom exceptions can be created by extending the already available exceptions. Programmer can throw a custom exception or a predefined Java exception. Mostly custom exceptions are created based on business conditions. Programmer can use the Java keyword ‘throw‘ to generate an exception. It is done by instantiating the exception class of choice and then thrown.
A thrown exception should be handled. If the program does not handles an exception, then it will be handled by the java run time environment. A block of code where an exception is expected should be surrounded by try – catch block. try indicates the start of the exception handling block and catch the end of the block. Following catch a block of code can be written which is the exception handling code block. This is the part the handles the exception. A catch will have an exception identified and it will catch only that type of exception. Type means the same exception and all its sub classes. There can be multiple catch blocks for a try block.
When a Java method is going to throw an exception, to indicate that as part of the method signature ‘throws‘ keyword should be used followed by the exception. It means that the caller of this method should handle the exception given in the throws clause. There can be multiple exceptions declared to be thown by a method. If the caller of that method does not handles the exception, then it propagates to one level higher in the method call stack to the previous caller and similarly till it reaches base of the method call stack which will be the java’s run time system.
finally
After catch block there can be one more block of code declared as ‘finally‘. Irrespective of whether an exception is thrown or not, the finally block of code will always be executed. Important piece of code that must be executed, even if a program fails belong to this finally block. Example would be closing a database connection, a file handle, etc.
try { // possible exception code block } catch (ExceptionTypeA exception1) { // handle exception of type ExceptionTypeA and all it subclasses } catch (ExceptionTypeB exception2) { // handle exception of type ExceptionTypeB and all it subclasses } finally { // guarantee block: executes always irrespective of exception }
This is a multi-part tutorial series and continue reading the next part of exception handling tutorial.
Comments are closed for "Exception Handling – Part I".
fantastic !! looking forward to this series
Can you add more examples please I am confused between throw and throws
Excellent approach… It will be helpfull if you elaborate how to identify location of TRY block.
Thank you once again………
Please clarify. Can we say exceptions are of 2 types(compile time and runtime)?, If so, how we justify compile time exceptions are exceptions? because the exception phenomena itself means at runtime?
I am a bit confused with the following statement”In exception handling we will be dealing only with run-time problems”.If so,how do we take Checked and Unchecked exceptions?
sir,
it is very useful for me. please elaborate the topic with examples.
Hi sir,
I am looking for collections and multithreading material plz send to me as soon as possible.
Hi Can u please explain about sessions in an web application.
Good Job, Look forward to the series sooner , thanks
Hi Joe,
I was wondering if you could provide examples of uploading data from excel file using java and jdbc.that would help many subscribers of your blog.
Simply Awesome and extremely helpful.
Ur site rocks and i will be looking forward to read your site material.
thanks
Very nice one.. Thank u so much.. :)
excellent awaiting more on this series..
You’d use throw to well, throw an exception from the Exception class, or a sub-type of it. throws is used to declare a list of exceptions that a method defines. For eg.,:
public void someMethod throws IOException {
if(notFavourableCondition) { // condition fails
throw IOException;
}
So with throws you can list the exceptions this method will generate, and with throw, the actual exception.
}
throw:
——
A devloper on your own can throw exception.
throws:
——-
if a devloper dont want to handle exception, then add throws in method signature.
please see example
1. throw example
class ThrowExample {
public static void main(String args[]) {
Account acc = null;
try {
demoproc(acc);
} catch(NullPointerException e) {
//handling thrown exception from method defination demoproc
System.out.println(“Recaught in main method : ” + e);
}
}
public void demoproc(Account a) {
//here you throwing exception by checking condition on your own
//now if acc is null then exception will be handled by calling main method
if(acc == null)
{
throw new NullPointerException(“In demoproc, received acc obj is null”);
}
else
{
acc.getName(); //if acc not null then calling method on acc obj
}
}
}
2. throws example
class ThrowsExample {
public static void main(String args[]) {
Account acc = null;
try {
demoproc(acc);
} catch(NullPointerException e) {
//handling thrown exception from method defination demoproc
System.out.println(“Recaught in main method : ” + e);
}
}
public void demoproc(Account a) throws NullPointerException{
acc.getName(); //here directly tried to call method on acc obj
// acc obj can be null, so it it is null then NullPointerException will be thrown
//here developer dont want to handle exception so throws added in method signature.
}
}
by throw u can throw any exception in ur program, but in case of throws u can throw only perticular exception
Thank Joe. Nice content, Please put example for everything.
Wells explained..
Thanks Joe
Respected Sir,
I have one Doubt
public static void main(String args[])
public static void main(String… args)
please tell the Difference between. My Doubt is only (String args[]) and (String… args) thats all. Suppose I put TWO Dots compile tile error occur.
[…] is a second in a the multi-part series for java exception handling. Previous tutorial serves as an introduction to java exception handling and this one takes it to the next […]
thanks Kanuj
Tapan, this part is just the introduction, continue reading coming parts of this tutorial and it has got lots of examples.
thanks Nagesh for the examples.
Farhaan, there is nothing as compile time exceptions. When you say exception in Java, it means run time problems. Exceptions can be thrown and handled at run time only.
When we compile the code what we get are compilation errors given by java compiler and it is no way related to exception handling.
Hani, I have written about checked and unchecked in Part II of this tutorial series: https://javapapers.com/core-java/exception-handling-2/
There is a separate tutorial on checked vs unchecked exceptions: https://javapapers.com/core-java/java-exception/explain-type-of-exceptions-or-checked-vs-unchecked-exceptions-in-java/
Bhaskar, continue reading the tutorial series you will get lots of examples.
Bhaskar, I am writing about collections immediately after the exception handling tutorial series. May be after that I will write on multithreading.
Viju, are you looking for this: https://javapapers.com/servlet/explain-the-methods-used-for-session-tracking/
Another great article. By the way, your website looks good. I am trying to create the same for myself. Any tips ?
Thanks Senthil.
I created this wordpress theme/design. Still lot of rough edges in this and need to smooth-en it.
if you give simple example for your each good explanation , that ll give more weightage..
thanks nagesh ur sample example helped me a lot
public class ThrowsSample {
public static void check () throws ArithmeticException
{
int a=42/0;
System.out.println(“Inside check method” +a);
}
public static void main(String args[])
{
try
{
ThrowsSample.check();
}
catch(Exception e)
{
System.out.println(“Exception caught:”+e);
}
}
}
public class ThrowSample {
//method to show use of throw
public static void check()
{
try
{
System.out.println(“Showing Throw”);
throw new ArithmeticException(“Explicit arithmetic exception”);
}
catch(Exception e)
{
System.out.println(“Exception caught “+e);
}
}
public static void main(String args[])
{
ThrowSample.check();
}
}
This is a feature of java known as var args. By declaring method with the arguments “String… args”, you are telling the compiler that you are not sure how many strings you will be passing when calling this method. You can call this method by 0 String, 1 String, 2 String, ..nString. JVM will create an array of string and pass it into your method. I hope it clarifies to an extent.
public static void main(String args[]) in this also we can call this method by 0 String, 1 String, 2 String, ..nString right?
Thankss to All for such a nice information
Thanks
[…] tutorial is part 3 of the exception handling series. Part I is about basics of exception handling. Part II is about exception hierarchy, stack traces, handling exception and best practices. Now in […]
This is great, thanks!
What happen when same exception occure in catch block?
Hi Joe,
It is great article, thanks for that.
I have a small question here,
As you mentioned in this article, logging exception and moving ahead is poor approach.
What could we do more than logging exception and showing error to user some way like error message on screen.
Anticipating reply.
Regards,
Mohan K
boss its actually a variable arguement wich behave just like a superset of an array
AirthmeticException is the sub class of run time exception….thus no need to declare them in the throws clause