Exception Handling

Author: Ravi Poswal

An exception is an error that can be handled programmatically. It is the runtime error when an exception occurs. A program can be terminated. There are several reasons why an exception could happen.

  • A user can enter invalid data.

  • The file cannot be found at the address location.

  • It may be network loss in communication.

Types of exception

  1. Checked exception

  2. Unchecked exception

Checked Exception

An exception examined at build time by the compiler is known as a checked exception. It is also called a compile-time exception—for example, SQLException, IOException, ClassNotFoundException, etc. 

Unchecked Exception

An exception that occurred at runtime is called a runtime exception. A logical error is an unchecked exception. Example: ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerException, etc.  

Code Example

 class Divide     
  { 
    public static void main(String arg[])
    { 
      try
       { 
         int x= Integer.parseInt(arg[0]); 
         int y= Integer.parseInt(arg[1]);  
         int z= x/y; 
           System.out.println("Result is :"+z); 
         }
catch(ArithmeticException e)
  {
   System.out.println("second no. must be non zero"); 
   } 
  catch (ArrayIndexOutOfBoundsException e)
  {
  System.out.println("Two Argument must be provided");
  }
  catch(NumberFormatException e) 
  { 
  System.out.println("Arguments must be numeric"); 
  }
  catch (Exception e)//generalized exception handler 
  {
  System.out.println(e); // general exception
  } 
   }}

FAQs

Exception handling is a mechanism to handle runtime errors using try, catch, throw, throws and finally blocks.

An exception is errors that can be handled using programmatically. It is the runtime error when an exception occurs. A program can be terminated. There are several reasons why an exception could happen.
• A user can be entered invalid data.
• The file cannot be found at the address location.
• It may be network loss in communication.

The try keyword allows you to define a block of code to be tested for errors when executing. A try block cannot be individual work. It is associated with a catch or, finally, block.

It is associated with a try block. This block cannot separate work. It is used for handling the exception. A single program can be multiple catches block but only try one block.

1. Checked Exception

Checked at compile time
Example: SQLException, IOException, ClassNotFoundException, etc.

2. Unchecked Exception

Occurs at runtime
Example: ArrayIndexOutOfBoundsException, AirthmeticException NullPointerException, etc.