Wednesday, 22 January 2014

EXCEPTION HANDLING IN JAVA

how to use exception handling

Exception-Handling Fundamentals

An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

Java exception handling is managed via five keywords:
  •   try
  •   catch
  •   throw 
  •   throws 
  •   finally
 If an exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch) and handle it in some rational manner.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. Any code that absolutely must be executed after a try block completes is put in a finally block.

General form of an exception-handling block:

try 
{
   // block of code to monitor for errors
}
catch (ExceptionType1 exOb) ss
{
   // exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
 {
   // exception handler for ExceptionType2
}
  // ...
finally
 {
// block of code to be executed after try block ends

}

Example for exception handling

class Division 
{
public static void main(String[] args) 
{
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
// try block
try
{
result  = a / b;
System.out.println("Result = " + result);
}
// catch block
catch (ArithmeticException e)
{
System.out.println("Exception caught: Division by zero.");
}
}
}






















































No comments:

Post a Comment