Skip to main content

How to handle Exception or Error in Java


Exception Handling.
                                   It is a mechanism to handle Error or Exception at runtime. It used create reliable software. The developer of code previous predict the error may occur and write code to handle that error. In object oriented programming all error are classified and defined as classes. For example ArithmeticException, ArrayIndexOutOfBoundsException, ClassNotFoundException, IOException, SQLException etc.

There five Keyword in Exception Handling they are try, catch, throw, throws, and finally.
  • The Try block used to monitor error in the statements. If error occurs it raises and throw.
  • Catch block used to caught exception thrown by try block and to handle that error.
  • Throw statement explicitly throw the Exception object.
  • Throws statement list type of exception the method might thrown.
  • Finally is default block, it will execute whether the exception occur or not. 

try 
// Monitor Error

catch (ExceptionType1) 

 // Handle ExceptionType1
catch (ExceptionType2) 

 // Handle ExceptionType2
}
catch (ExceptionType3) 

 // Handle ExceptionType3
}
finally
{
//statement
}

The Try block can thrown any type exception and the match Catch Block type will handle that exception or error

The Exception Class Hierarchy

Exception Handling java
The Throwable is Super Classs of all exception classes, from that two derived class Exception and Error. Exception class is software runtime exception for example SQLException, IOException, ArrayException, ArithmeticException, ClassNotFoundExceeption etc.
The Error is hardware exception type ie StackOverFlow, VirtualMachineError etc.

Example

import java.io.*;
class ExceptionDemo
{
static void throwone()
{
try

int a =1;
a=a/0; //Divide by Zero Error
}
catch (ArithmeticException de)
{
System.out.println("Divide by zero Error "+de);
}
}
public static void main(String[] args)
{
throwone();
}
}

In the above program we try divide a number by 0, which result in infinite. so Try block raise ArithmeticException. Catch block caught and handle that exception.

Throw
The throw keyword used to explicitly throw the error. 

class ExceptionDemo
{
static void throwone()
{
System.out.println("Inside Throw One");
try
{
int a[]=new int[5];
a[10]=100;
throw new ArrayIndexOutOfBoundsException();
}
catch (ArrayIndexOutOfBoundsException ai)
{
System.out.println("Exception 1 : "+ai);
}
}
static void throwtwo()
{
System.out.println("Inside Throw Two");
try
{
int n[]=new int[-5];
throw new NegativeArraySizeException();
}
catch (NegativeArraySizeException na)
{
System.out.println("Exception 2 : "+na);
}
}
public static void main(String[] args)
{
throwone();
throwtwo();
}
}


Thank You. Like Share and Subscribe 👍 folowlect.com

Comments