You can define your own exception class for your application specific purposes. The exception class is created by extending the java.lang.Exception
class for checked exception or java.lang.RuntimeException
for unchecked exception. By creating your own Exception classes, you could identify the problem more precisely.
package org.kodejava.basic;
public class CustomExceptionExample {
public static void main(String[] args) {
int x = 1, y = 0;
try {
int z = CustomExceptionExample.divide(x, y);
System.out.println("z = " + z);
} catch (DivideByZeroException e) {
e.printStackTrace();
}
}
public static int divide(int x, int y) throws DivideByZeroException {
try {
return (x / y);
} catch (ArithmeticException e) {
String m = x + " / " + y + ", trying to divide by zero";
throw new DivideByZeroException(m, e);
}
}
}
package org.kodejava.basic;
class DivideByZeroException extends Exception {
DivideByZeroException() {
super();
}
DivideByZeroException(String message) {
super(message);
}
DivideByZeroException(String message, Throwable cause) {
super(message, cause);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024