Exception Handling in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

An exception is an event that disrupts the normal flow of the application or program during execution. When an error occurs in a method in runtime, the error is handled by a class Exception.

Let us consider a very simple example, where a number is being divided by another number. At any instance, if the divisor is 0 (zero), an error will occur, which will disrupt the normal flow of the program.

All the exceptions in Java are handled by five keywords: try, catch, throw, throws and finally. This tutorial will cover the use of those keywords with some examples.

try-catch block

If you run the following program, the program terminates immediately after an exception occurred. Thus, the code segment followed by the line where the exception occurred does not execute.


public class TestMain { public static void main(String[] args) { int x = 10; int i = 0; System.out.println("I am before suspicious block."); System.out.println((x / i)); System.out.println("I am after suspicious block."); } }

To avoid the situation, the exception is handled using try-catch blocks. The line(s) of code that may generate an exception is included in try block. If an exception occurs, the exception is handled in catch block.

In the following program, though an exception is generated, the program does not terminate immediately. After handling the exception, the remaining lines of the program will execute without any error.


public class TestMain { public static void main(String[] args) { int x = 10; int i = 0; System.out.println("I am before try catch block."); try { System.out.println((x / i)); } catch (Exception e) { e.printStackTrace(); } System.out.println("I am after try catch block."); } }


try-catch-finally block


If some instructions are written in a try block and an exception occurs before executing all the lines of the try block, the program control immediately moves to catch block without executing the rest of the lines of the try block. But if the rest of the lines contain some instructions which are to be executed even if an exception occurs, the instructions are to be added in finally block. The following example shows how to use finally with try and catch.


public class Test { public static void main(String[] args) { int x = 10, y = 5; try { System.out.println("The result is: " + x / y); } catch (ArithmeticException e) { System.out.println("The exception is" + e); } finally { System.out.println("I am finally."); } } }

According to requirements, try-catch or try-catch-finally blocks can be nested. Moreover, multiple catch clauses can be associated with one try block. Remember that if you add multiple catch clauses with a try , the exceptions are to be handled properly. The sub-exception class should be preceded by super-exception class. For example, ArithmaticException should be preceded by Exception class.


Throwing an Exception


Sometimes, an exception may not be handled in the method where it occurs. Thus the method throws the exception to the caller method to be handled. In the following example, the div() method throws the exception to the caller method. And the exception is actually handled in the caller method.

 A.java
public class A { int div(int a, int b) throws ArithmeticException { return a / b; } }
TestMain.java
public class TestMain { public static void main(String[] args) { try { System.out.println(new A().div(10, 0)); } catch (Exception e) { e.printStackTrace(); } } }

User Defined Exception


Exceptions are not built-in always. Sometimes, developers create a lot of exceptions according to their requirements. Thus in the following program, we will discuss how to create a user-defined exception.

If you want to create an exception, the class should inherit Exception class. In the following example, we are creating MyException class. If withdraw method is invoked with an amount greater than the available balance, the exception needs to be thrown. In this example, the account balance is 10000, the withdrawal amount is 20000. Thus the exception is generated.


public class MyException extends Exception { private static final long serialVersionUID = 1L; public MyException(String str) { System.out.println(str); } }

public class Account { int acc_bal = 10000; void withdraw(int amount) throws MyException { if (amount > acc_bal) { throw new MyException("Insufficient balance"); } } }

public class TestMain { public static void main(String[] args) { try { new Account().withdraw(20000); } catch (MyException e) { e.printStackTrace(); } } }


How do handle User Defined Exceptions?


User-defined exceptions can be handled in a similar way to built-in exceptions. The following example shows how user-defined exceptions can be handled using throws or try-catch.


public class TestExcep { int accbal = 500; void check() throws MyException { if (accbal < 1000) { throw new MyException(); } else { System.out.println("Sufficient balance."); } } void check1() { if (accbal < 1000) { try { throw new MyException(); } catch (MyException e) { e.printStackTrace(); } } else { System.out.println("Sufficient balance."); } } }

public class MainExcep { public static void main(String[] args) { try { new TestExcep().check(); } catch (MyException e) { e.printStackTrace(); } new TestExcep().check1(); } }


Remember that an exception may occur in the catch block as well as finally block. Sometimes, you may need to add a try-catch in the catch block or in finally block.




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.