While coding, we may face few compile time errors because of incorrect syntax and those errors can be removed by re-correcting our syntax. Similarly, we may also come across Run-Time errors caused by exceptions and those errors also needed to be handled. Java provides us with an important feature that allows us to handle those run time exceptions. That feature is called Exception Handling in Java. In this article we will look about this interesting topic.
What is an Exception?
An Exception is an unexpected event that occurs in the runtime of a program(i.e., an exception is a Runtime error), by which normal flow of the program gets interrupted and program will be terminated abnormally. In such cases, system generates a message, which may not be understandable to the user. But no worries, such type of exceptions occurred during runtime can be handled in java by providing user friendly message.
What is Exception Handling in Java?
Whenever, an exception occurs and if it is not handled properly, flow of the program will be terminated and system generates an error message as below.
Below is an example of exception generated by the system:
Exception in thread "main" java.lang.ArithmeticException: / by zero at Exceptiondemo.main(ExceptionDemo.java:9)
Above mentioned message may not be understandable to the user, what’s the actual issue is. In such cases, we handle exceptions to generate message in user friendly language. By this exception handling,normal flow of the program will be maintained and statements after the exception will be executed successfully.
Hierarchy of Java Exception Classes
Types of Exception
There are two types of exception. They are:
1) Checked Exceptions.
2) Unchecked Exceptions.
Checked Exceptions: Â The Classes that extend Throwable class other than RunTimeException are known as checked exceptions. Checked exceptions are checked at compile-time. For Example, IO Exception, SQL Exception etc..
Unchecked Exceptions:Â The Classes that extend RunTImeException are known as unchecked exceptions. Unchecked exceptions are checked at runtime. For Example, ArithmeticException, NullPointerException, ArrayOutOfBoundException etc..
Keywords for Exception Handling in Java
There are 5 keywords used for exception handling in java.
- try
- catch
- finally
- throw
- throws
Try Block
The try block encloses set of statements from which an exception may occur. It must be used within the method. A try block is always followed by a block which can handle the exception that was thrown by try block, that can be either catch block or finally block or both.
Syntax of try block:
try { //set of statements which may throw exception }
Catch Block
Catch block is where we can handle exceptions that are thrown from try block. It must be always followed by a try block. A try block may contain any number of catch blocks. Each different catch block may contain different exception. When an exception thrown by try block, corresponding catch block which handles that exception will be executed.
Syntax of try catch block:
try { //set of statements that may cause an exception } catch(exception e(object){}
Example for try-catch block:
Exception occurred in try block is handled by corresponding catch block. A try block may have any number of catch blocks. But, its better to place a generic exception handler catch block after all catch blocks which displays a generic message. A generic exception handler handles any type of exception. That block will only execute, if the exceptions was not handled by other catch blocks.
public class TrycatchDemo{ public static void main(String args[]){ int a = 0; int b =23; try{ int fraction = b/a; System.out.println("Statement within try block"); } catch(ArithmeticException e){ System.out.println("Handled exception from catch block "+e); } System.out.println("I'm out of try-catch block"); } }
Output:
Exception Handled by catch block java.lang.ArithmeticException: / by zero I'm out of try-catch block
Example for Multiple catch blocks:
As we already discussed, a single try block may have any number of catch blocks followed. A generic catch block is able to handle any type of exception. No issue, even if there is no exception thrown from try block followed by catch block. That catch block will be ignored.
public class MultiplecatchDemo { public static void main(String args[]) { try { int a[]=new int[3]; a[2]=23/0; System.out.println("Statement within try block"); } catch(ArithmeticException e) { System.out.println("ArithmeticException handled by first catch block"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException handled by second catch block"); } catch(Exception e) { System.out.println("Generic exception handler catch block"); } System.out.println("I'm Out of try-catch block"); } }
Output:
ArithmeticException handled by first catch block I'm Out of try-catch block
Finally Block
Finally block consists of set of statements, which will always be executed whether exception is handled or not. It is followed by try block or catch block. For each single try block, there may be any number of catch blocks but, only one finally block.
Example for finally block:
Case 1: No exception occurred
public class FinallyDemo1 { public static void main(String args[]) { try { int value=46/2; System.out.println(value); } catch(NullPointerException e) { System.out.println(e); } finally { System.out.println("Finally block will execute always"); } System.out.println("I'm out of try-catch-finally block"); } }
Output:
23 Finally block will execute always I'm out of try-catch-finally block
Case 2: Exception occurred and not handled
public class FinallyDemo2 { public static void main(String args[]) { try { int value=2/0; System.out.println(value); } catch(NullPointerException e) { System.out.println(e); } finally { System.out.println("Finally block will execute always"); } System.out.println("I'm out of try-catch-finally block"); } }
Output:
Finally block will execute always Exception in thread "main" java.lang.ArithmeticException: / by zero at FinallyDemo2.main(FinallyDemo2.java:7)
Case 3: Handled occurred exception
public class FinallyDemo3 { public static void main(String args[]) { try { int value=23/0; System.out.println(value); } catch(ArithmeticException e) { System.out.println(e); } finally { System.out.println("Finally block will execute always"); } System.out.println("I'm out of try-catch-finally block"); } }
Output:
java.lang.ArithmeticException: / by zero Finally block will execute always I'm out of try-catch-finally block
Java throw keyword
Java throw keyword is used to throw an exception explicitly. That can be either checked or unchecked exception, It can also be used to throw custom exceptions. Let’s discuss about it later.
Syntax:
throw new exception_class("print statement");
Example:
public class ThrowDemo { public static void main(String[] args) throws Exception { try { System.out.println("Statement 1"); try { System.out.println("Statement within inner try block"); throw new Exception("threw exception within inner try block "); } finally { System.out.println("Statement within first finally block"); } } catch(Exception e) { System.out.println("Exception handled by try block"); } finally { System.out.println("Final finally block"); } } }
Output:
Statement 1 Statement within inner try block Statement within first finally block Exception handled by try block Final finally block
Java throws keyword
Throws keyword is used for handling checked exceptions. Multiple exceptions can be declared using throws keyword.
Syntax of java throws keyword :
return_type method_name() throws exception_class_name { // set of statements }
Advantage of throws keyword over using try-catch block:
Let’s consider it with an example. Whenever we have a single method with some set of statements and that may throw any exception, in that case we may go with try-catch
Example:
public void ThrowsDemo1() { try { // Statements from which exception may occur } catch (ArithmeticException e) { // statements for exception handling in java } catch (NullPointerException e) { // statements for exception handling in java } }
Similarly, if we have several number of methods with set of statements that may cause exceptions, in that case we go with using throws keyword as below:
public void ThrowsDemo2() throws ArithmeticException, NullPointerException { // Statements from which exception may occur } public static void main(String args[]) { try { ThrowsDemo2(); } catch (ArithmeticException e) { // statements for exception handling in java } catch (NullPointerException e) { // statements for exception handling in java } }
That’s about exception handling in Java. Comment below in case of any queries. We’ll discuss more beginner topics in our future articles.