Java ProgrammingLearn to handle exceptions in java

Learn to handle exceptions in java

In this tutorial we will learn about exceptions, how to handle exceptions with try, catch and finally block, how to throw an exception, how to implement checked exception at compile time, how to implement unchecked exception at run time and how to create custom exception in java along with examples.

  • To have in depth knowledge lets learn to handle exceptions in java through the steps given below :

  1. Handling Exceptions try, catch and finally blocks, How to throw exception : –
    • Handling Exception : When error condition throws an exception object, if that exception object is not caught and handled properly then the interpreter will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by error condition and then display an appropriate message for taking corrective actions. This whole task is called as exception handling.
    • Error handling code performs the following tasks: –
      i. Hit the exception.
      ii. Throw the exception.
      iii. Catch the exception.
      iv. Handle the exception.

      handling exceptions

    • Try Block : Java uses a keyword try to beginning a block of code that is expected to cause an error condition and throw an exception. The try block may have one or more statements that could generate an exception. If one statement generates an exception, the remaining statements in the block are skipped and executions bounce to the catch block that is located next to the try block. Every try block must be followed by at least one catch block, else compilation error will occur. If for some sort of reason the try block is not throwing any exception, then the catch block will be fully avoided and the program continues.
    • Catch Block : The keyword catch is used for defining catch block. Catch block is added immediately after try block. It is used for catching the exception thrown by the try block. The catch block works like method definition. With a single parameter the catch statement is passed, which is reference to the exception object thrown by the try block. If the catch parameter matches with the type of exception object, then the exception is caught and statement in the catch block will be executed. Otherwise, the exception is not caught and the default exception handler will cause the execution to terminate.
    • Example : This example shows that how try catch block is used in java class.

      public class ExceptionPro 
      {
      public static void main(String[] args)
      {/*in try block write code which is cause an error condition and throw an exception*/
      try
      {//for loop which check condition 5 to 0
      For (int i=5; i>=0; i--)
      {//print on console
      System.out.println (16/i);
      }
      }
      Catch (Exception e)//catch exception which thrown by try
      {//print on console
      System.out.println ("Exception: "+e.getMessage ());
      /*this method print a stack trace for this Throwable object on the error output stream*/
      e.printStackTrace ();
      }
      System.out.println ("After for loop...");//print on console
      }
      }
      

      Output

      3
      4
      5
      8
      16
      Exception: / by zero
      java.lang.ArithmeticException: / by zero
      			at ExceptionPro.main (ExceptionPro.java:9)
      After for loop...
      


    • Finally Block : Finally keyword is used for the defining the finally block. This finally statement can be used to handle an exception that is not caught by any of the previous catch statements; finally block can be used to handle any exception generated within a try block. This is added immediately after the try block or after the catch block. When it is defined, this is guaranteed to execute, regardless of whether or not in exception is thrown.
    • Finally Block

      Example : This example shows that how finally block is used in java class.

      public class Try 
      {
      public static void main(String args[])
      {
      int j=20;
      int k=10;
      /*in try block write code which is cause an error condition and throw an exception*/
      try
      {
      int x=j/(k-k);      //Exception here
            
      }
      //catch exception which thrown by try
      catch(ArithmeticException e)
      {
      System.out.println ("Exception Message: "+e.getMessage());
      }
      /*finally block is executed at least once if exception occurs or not*/
      finally
      {
      int y=j/k;
      System.out.println ("y = "+y); //print output
      }
      }
      }
      

      Output :

      Exception Message: / by zero
      y = 2
      

    • How to throw an exception : An exception must be thrown first before catching it. Its meaning is that there is a code somewhere in the program that could catch the exception which is thrown by some other code in the program. You can use throw keyword with an object reference to throw an exception. Note that instances of any subclass of the Throwable class are Throwable objects. Throw keyword is used for throwing an exception to increase user defined exception i.e. by extending the exception class if user define its own exception, then that exception can be increases by only using throw keyword. Throw keyword must be defined in the method which is must be defined using throws keyword or in the try catch block.
    • Example : This example shows that how to throw an exception in java class.

      public class ExxeptionPro 
      {
      public static void main(String args[])
      {
      System.out.println (show());//print show()
      }
      public static int show()
      {
      try
      {
      throw new Exception();//here new exception thrown
      }
      catch(Exception e)
      {
      throw new Exception();//caught an exception
      }
      finally
      {
      return 16;//finally print value 16
      }
      }
      }
      

      Output :

      16


  2. Checked Exceptions at compile time : –
  3. Checked exceptions are nothing but the exceptions that are checked at compile time. In this case the program will give a compilation error, when a method is throwing a checked exception then it should declare the exception using throws keyword or it should handle the exception using try-catch block. Compile time exception is nothing but the exception at the time of compiling the java program exception is thrown by java virtual machine.

    Checked Exceptions

  4. Unchecked Exceptions at run time : –
  5. Unchecked exceptions are nothing but the exceptions that are not checked at compile time. In this case the program won’t give you a compilation error; if a program is throwing an unchecked exception and even if you didn’t declare or handle that exception. Most of the times these exceptions arise during the user-program interaction due to the wrong data implemented by user. All unchecked exceptions are sub classes of RuntimeException class.

    Example : This example shows that how to throw an unchecked exception in java class.

    class UncheckedExce 
    {
    public static void main(String args[])
    {
    int a=10;
    int b=0;
    /*here I'm dividing an integer with 0 it should throw ArithmeticException*/
    int div=a/b;//exception throw here at run time.
    System.out.println (div);
    } 
    }	
    

    Output :

    Exception in thread "main" java.lang.ArithmeticException: / by zero
    at UncheckedExce.main (UncheckedExce.java:9)
    

    In this above example you compile this code and it will compile successfully however when you will run it, it will throw ArithmeticException. That means here it is clearly shows that unchecked exceptions are checked at compile time.

    Unchecked Exceptions

  6. Creating Custom Exceptions : –
  7. Custom exceptions are nothing but the exceptions that are defined by the user and extended by exception class or RuntimeException class. You can use this custom exception by keyword throw.

    Syntax :

    throw new Throwabl’e subclass;

    Example : This example shows that how to create custom exception in java class.

    class MyException extends Exception//extends with Exception class
    {
    MyException (String msg) //define parameterized constructor
    {
    /*The MyException(String) constructor calls super(msg) to construct a throwable with the specified detail message.*/
    super(msg);
    }
    }
    class TestMyExc
    {
    public static void main(String[] args)
    {
    int a=5, b=1000; //declare variable
    try //throw exception
    {
    float c=(float)a/(float)b;
    if(c<0.01) //check condition
    {
    throw new MyException("Number is tooooo small");
    }	
    }
    catch (MyException me)
    //object me contain error message is caught by catch block
    {
    System.out.println ("Caught My Exception");
    System.out.println (me.getMessage ()); //display message
    }
    finally //finally will execute at least one time at last 
    {	
    System.out.println ("Hi this is Finally Block");
    }
    }
    
    }
    

    Output :

    Caught My Exception
    Number is tooooo small
    Hi this is Finally Block
    

    Here, we use user-defined subclass of Throwable class. Note that Exception is a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught.

Thus, we have learned successfully about how to handle exceptions in java.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -