Hi everyone in this blog I’m explaining about how to handle the exception.
Java try-catch:
Try block is used to enclose the code that might throw an exception. It must be used within the method. Try block must be followed by either catch or finally block.
The syntax of try-catch:
try
{
//Code that may throw exception
}
catch(Exception_Class_Name ref){}
Syntax of try-finally:
try
{
//Code that may throw exception
}
finally
{
//code that you want to execute in any condition
}
Java catch block:
Java catch block is used to handle the exception. It must be used after try block only. You can use multiple catch block with a single try block.
The problem without use exception handling:
class Sample
{
public static void main(String … s)
{
int d=10;
int r=d/0;
System.out.println(“Rest of the code….”);
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/by zero
Solution by use exception handling:
class Sample
{
public static void main(String … s)
{
Try
{
int d=10;
int r=d/0;
}
Catch(ArithmeticException ex)
{
System.out.println(“Rest of the code….”);
}
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/by zero
Rest of the code….
Leave Comment