Java – Exception Handling

Posted on Updated on

Stuff happens. The file isn’t there. The server or database is down. No matter how good a programmer you are, you can’t control everything. Things can go wrong, very wrong. When you write a risky method, you need to handle the bad things that might happens. But how do you know when a method is risky and when do you put the code to handle the exception situation?
Basically, an Exception is runtime error. All exceptions occurs only at runtime but some exceptions are detected at compile time and other some others at runtime. The exception that are checked at compilation time by Java compiler are called ‘checked exceptions‘ while the exceptions that are checked at runtime by the JVM are called ‘unchecked exceptions‘.

Exception Hierarchy

Exception Hiearrchy

Throwable is a class that represents all errors and exceptions which may occur in Java. While Exception is the superclass of all exception in java.

Let’s have an example which shows why Exception Handling is important.

Output:

The above given example clearly shows us that why it is important to handle exceptions.

Exception Handling

1). The programmer should observe the statement in their program to check if there is possibility of exception. Such statement should be enclosed within a try block.

The importance of try block is that even if some exception occurs inside it, the program will not be terminated. When JVM knows that there is an exception, it stores the exception details in an exception stack and jumps into a catch block.

2). The catch block helps programmer to display the exception details to the user. This helps programmer to understand that there is some error in the program and also displays an user-friendly error message.

3). Lastly, the programmer should perform clean operation like closing the file, database connection, terminating thread etc. The programmer write this code in the finally block.

 

Lets revisit our previous example with Exception Handling –

Output:

 

Example – Multiple Exception Handling

Output:

 

Now correct the ArithmeticException and again execute the program –

Output:

Throws Clause

Even if the programmer is not handling runtime exception, the Java compiler will not give any error related to runtime exception. But programmer should handle checked exception. So in this case, if programmer does not want to handle the checked exception, he/she should throw them out using ‘throws’ clause. Otherwise there will be an error flagged by Java compiler which can be easily seen in Eclipse or other related IDE.

Output:

 

Programmer can also define their own exception. Click here to know more.

Stay tuned for more updates !

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.