Java Exception Handling

Introduction

Java exception handling is managed via five keywords:

  • try
  • catch
  • throw
  • throws
  • finally

This is the general form of an exception-handling block:

try {  /*from w  ww  .j a  va2 s  .c om*/
// block of code to monitor for errors  
}  
catch (ExceptionType1 exOb) {  
// exception handler for ExceptionType1  
}  
catch (ExceptionType2 exOb) {  
// exception handler for ExceptionType2  
}  
finally {  
// block of code to be executed after try block ends  
} 

Here, ExceptionType is the type of exception that has occurred.

The following code demonstrates throwing an exception when a divide-by-zero occurs.


public class Main
{
   // demonstrates throwing an exception when a divide-by-zero occurs
   public static int quotient(int numerator, int denominator)
   {/*from   w ww  . j a  va  2s.c  o  m*/
      return numerator / denominator; // possible division by zero
   }

   public static void main(String[] args)
   {
      int numerator = 1;
      int denominator = 0;

      int result = quotient(numerator, denominator);
      System.out.printf("%nResult: %d / %d = %d%n", numerator, denominator, result);
   }
} 

public class Main {
    public static void main (String[] args) {

        try {/* w  w w .j  ava 2s.  com*/
            int a = 5/0;
        }  catch (Exception e) {
            e.printStackTrace();
        }

    }
}



PreviousNext

Related