Exception handling using try-catch block :
There are five keywords used in Exception handling
1. try
2. catch
3. finally
4. throw
5. throws
try block:
Enclose the code that might throw an exception in try block.It must be used within the method and must be followed by either catch or finally block.
Syntax of try with catch block
try
{
...
}
catch(Exception_class_Name reference_variable_name) // i.e. catch(RuntimeException ex) { }
{
.......
}
catch block:
Catch block is used to handle the Exception.It must be used after the try block.
Problem without exception handling:
class Test{
public static void main(String []args){
int data=50/0;
System.out.println("rest of the code.....");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
As you see in the above example, rest of the code is not executed i.e. rest of the code..... statement is not printed. But if we want to executed the rest of code..... we have to use Exception handling.
Solution by exception handling:
class Test{
public static void main(String []args){
try{
int data=50/0;
}
catch(ArithmeticException ex)
{
System.out.println(ex);
}
System.out.println("rest of the code.....");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code.....
Note: Now, as you see in the above example, rest of the code is executed i.e. rest of the code..... statement is printed.
Next>> Multiple catch block in Exception Handling
There are five keywords used in Exception handling
1. try
2. catch
3. finally
4. throw
5. throws
try block:
Enclose the code that might throw an exception in try block.It must be used within the method and must be followed by either catch or finally block.
Syntax of try with catch block
try
{
...
}
catch(Exception_class_Name reference_variable_name) // i.e. catch(RuntimeException ex) { }
{
.......
}
catch block:
Catch block is used to handle the Exception.It must be used after the try block.
Problem without exception handling:
class Test{
public static void main(String []args){
int data=50/0;
System.out.println("rest of the code.....");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
As you see in the above example, rest of the code is not executed i.e. rest of the code..... statement is not printed. But if we want to executed the rest of code..... we have to use Exception handling.
Solution by exception handling:
class Test{
public static void main(String []args){
try{
int data=50/0;
}
catch(ArithmeticException ex)
{
System.out.println(ex);
}
System.out.println("rest of the code.....");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code.....
Note: Now, as you see in the above example, rest of the code is executed i.e. rest of the code..... statement is printed.
Next>> Multiple catch block in Exception Handling
No comments:
Post a Comment