Write A Program In Java To Develop User Defined Exception For Divide By Zero Error
In this program, we will create a exception that handle divide by zero error.
Before demonstrate the program we will understand the concept of exception.
In java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions can be caused by various reasons such as user input errors, hardware failures, or resource exhaustion.
When an exception occurs, the java runtime system creates an exception object and throws it. This object contains information about the error that occurred, including its type and a detailed message.
To handle exceptions in your code, you can use a try-catch block. The try block contains the code that might throw an exception. If an exception is thrown within the try block, it is caught by the catch block that follows it. The catch block contains code that handles the exception and takes appropriate action.
Here’s an example:
try { // Code that might throw an exception} catch (ExceptionType e) { // Code to handle the exception}
In this example, if an exception of type exceptiontype is thrown within the try block, it will be caught by the catch block and handled appropriately.
Java also provides several built-in exception classes for common error conditions such as arithmeticexception, nullpointerexception, and ioexception. You can also create your own custom exceptions by extending one of the existing exception classes.
Here’s an example program that demonstrates how to create a user defined exception for divide by zero error:
class DivideByZeroException extends Exception { public DivideByZeroException() { super("Cannot divide by zero!"); }}
public class UserDefinedExceptionExample { public static void main(String[] args) { int numerator = 10; int denominator = 0;
try { if (denominator == 0) { throw new DivideByZeroException(); } else { int result = numerator / denominator; System.out.println("Result: " + result); } } catch (DivideByZeroException e) { System.out.println(e.getMessage()); } }}
Cannot divide by zero!