public class TC_Demo
{
public static void main(String[] args)
{
int a=10;
int b=5,c=5;
int x,y;
try
{
x = a / (b-c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
y = a / (b+c);
System.out.println("y = " + y);
}
}
- See more at: http://www.java2all.com/1/1/16/86/Technology/CORE-JAVA/Exception-Handling/Try-and-catch#sthash.RPy312Fu.dpuf
{
public static void main(String[] args)
{
int a=10;
int b=5,c=5;
int x,y;
try
{
x = a / (b-c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
y = a / (b+c);
System.out.println("y = " + y);
}
}
Output :
Divide by zero
y = 1
Note that program did not stop at the point of exceptional condition.It catches the error condition, prints the error message, and continues the execution, as if nothing has happened.
If we run same program without try catch block we will not gate the y value in output. It displays the following message and stops without executing further statements.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Thrw_Excp.TC_Demo.main(TC_Demo.java:10)
Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero.
No comments:
Post a Comment