Junior — Middle
Is it possible to define a custom exception with compile-time checking?
sobes.tech AI
Answer from AI
Yes, in Java, you can define your own exception that will be checked at compile time. To do this, you need to create an exception class that inherits from the Exception class (but not from RuntimeException). Such exceptions are called checked exceptions. The compiler requires them to be handled either with a try-catch block or declared in the method signature with throws.
Example:
public class MyCheckedException extends Exception {
public MyCheckedException(String message) {
super(message);
}
}
public void someMethod() throws MyCheckedException {
// ...
throw new MyCheckedException("Error!");
}
If you inherit from RuntimeException, then the exception will be unchecked, and compile-time checking will not be required.