Exception Handling
What is Exception?
Exception means 'abnormal condition'.
The exception is also as the run-time error in java.
It throws by Java Runtime Environment.(JRE).
The exception handling is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.
In Java, Exception handling is done using five keywords: try, catch, throw, throws, and finally.
#1 Try
Try is a block. The statement that can generate an exception is placed in the try block.
#2 Catch
If an exception is generated in the try block then, its object is created and throws.
This object caught in the catch block.
#3 Throw
Normally, the exception is generated by some statements but to manually create and throws an exception object throws keyword is used.
#4 Throws
When a method can generate exception this method is specified by "throws" keyword.
#5 Finally
Finally is a block. Which execute compulsory whether the exception is caught or not.
There are two types of exception:
1. Run-time Exception
Ex: ArrayIndexOutOfBoundsException.
2. IOException
Ex: IOException is trying to read past to the time of a file etc.
Example
class Exdemo
{
public static void main(String args[])
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[0]);
int c=a/b;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Enter two value..");
}
catch(ArithmeticException ae)
{
System.out.println("Zero not valid");
}
finally
{
System.out.println("Finally call");
}
}
}