Java – Exception Handling

It is a resizable array or a dynamic array. It uses this dynamic array mechanism to store its elements. ArrayList class is found in the java.util package in java.

There are two types of errors:

  1. Compile time errors
  2. Runtime errors

Compile time errors : Often categorized as syntax(when syntax is not correct) and semantic(when syntax is correct but the usage is not) errors.

Example –

syntax error : when you write floa a; instead of float a; or

semantic error : when you declare a variable float a; again after few lines, float a;

Runtime errors : Also called as Exception errors. Exception is an unexpected event that disrupts the normal flow of execution of a program.

Example – ArithmeticException, NullPointerException, NumberFormatException, ArrayIndexOutOfBoundsException

Arising of exceptions is something which is not in developers control.

Why do we need to Handle Exceptions ?

In Real world life scenario consider a case when you have made an application which has a User Interface and it connects to a database and database goes down because of maintenance or is locked because of some failure.

How will a user/customer come to know that there is an issue with the database, will you throw an error on there face ? or catch this database exception and handle it gracefully showing proper message to the user.

So if you don’t wanna let your user/customer run away from your application by seeing the technical errors which they do not understand we handle the exceptions gracefully by catching these exceptions and return meaningful messages to the user/customer of the downtime or anything like that OR a better way for this example is to switch to a backup database in case the main database is not responding/throwing error.

How to Handle Exceptions ?

To handle a situation like in above scenario, we try to write a code which can handle this kind of exception. In this example of database failure we write a code to switch to another backup database so that our application is up and running without any interuption.

It can be written in an “if else block” as well BUT what if there is some other database exception which you did not forsee or cover in your code, what do you do then ? For this reason we need an Exception Handler.

Java and many other languages provides Exception Handling classes/frameworks which can handle it gracefully.

Try Catch finally Block

Try block : Program statements that you think can raise exceptions are contained within a try block.

Catch block : Write the code to handle exception in graceful manner.

Finally block : Write the code which you want should execute at any cost no matter exception is raised or not.
Example : closing session/database/file connection after execution of program.

Syntax of writing try-catch-finally block

try{
    //Code where you expect an exception would occur
  }
catch (exceptiontype name){
    //Code to handle the exception if it occurs
  }
finally{
    // example : connection.close();
  }

Actual Example :

public static void main(String[] args) {
    int a=0;
    int b=10;
    System.out.println("before dividing");
    try {
      System.out.println(b/a);
    }
    catch(ArithmeticException e) {
      e.printStackTrace();
    }
    System.out.println("after dividing");
}

OUTPUT

    
before dividing
java.lang.ArithmeticException: / by zero
  at com.test.exceptions.TestExceptions.main(TestExceptions.java:10)
after dividing    

Example : with finally block

public static void main(String[] args) {
    int a=0;
    int b=10;
    System.out.println("before dividing");
    try {
    System.out.println(b/a);
    }
    catch(ArithmeticException e) {
      e.printStackTrace();
    }
    finally {
      System.out.println("after dividing finally block");
    }
}

OUTPUT

before dividing
java.lang.ArithmeticException: / by zero
at com.test.exceptions.TestExceptions.main(TestExceptions.java:10)
after dividing finally block   

Hierarchy of ArrayList class

Diagram comes here

Java Exception Keywords

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause.

Difference between Checked and Unchecked Exceptions

In java there are 2 types of exceptions.

  • Checked Exceptions
  • Unchecked Exceptions
S.NoCheckedUnchecked
1Checked exceptions are the exceptions which are checked at compile time.Unchecked are the exceptions that are not checked at compiled time.
2IOExceptions class is compile time.In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Summary

So here we are, we hope now you are confident and know how to use Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Leave a Comment