Exception Handling (Arithmetic Exception) – Divide by Zero

So after a brief explanation on Exception Handling, today we are goona implement “Exception Handling” (Arithmetic Exception) by taking a very common example of “Divide by Zero”.

So we all know that divide by zero doesn’t make a sense, and our system also doesn’t know what to do in this situation? so this causes an Exception which should be handled and is a good habit of programming. Now we are gonna take a look at such exception…

class ExceptionHandling
{
public static void main(String [] args)
{
System.out.println("\n------------------------------------------");
System.out.println("Divide by Zero! (ArithmeticException)");
System.out.println("------------------------------------------\n");
int result;
try
{
result = 5/0;
}
catch(Exception e)
{
System.out.println(e);
System.out.println("------------------------------------------");
}
}
}

Here there are try block and catch block. In the try block the condition is given where an exception can be caused, therefore here it is given result = 5/0; which is an exception.
When the code runs the code follows try block and if exception is generated it is redirected to the catch block where we’ve handled the exception as catch(Exception e) and printed the type of Exception which is “java.lang.ArithmeticException: / by zero”. You can checkout the Output given below.

Output

Author Description

humanz

Our mission is to bring the affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world. - Follow @program_guide

No comments yet.

Join the Conversation