Exception Handling in JAVA 2
Java try-catch
Java Exception Handling Keywords.
There are 5 keywords used in java exception handling.
1) try
2) catch
3) finally
4) throw
5) throws.
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch.
try {
//code that may throw exception
} catch(Exception_class_Name ref){
// Handle exception
}
Syntax of try-finally block.
try {
//code that may throw exception
} finally {
// code to excecute anyhow
}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
Example using Try and catch
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Output :
Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transfered outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program controls continue with the next line in the program. Thus the line "After exception is handled" is printed.
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )