Junior — Middle
Is it possible to convert a custom exception inheriting from RuntimeException to the RuntimeException type?
sobes.tech AI
Answer from AI
Yes, a custom exception inheriting from RuntimeException is its subclass and can be cast to RuntimeException without any issues.
Example:
class MyException extends RuntimeException {}
try {
throw new MyException();
} catch (RuntimeException e) {
// Here e is a RuntimeException, although it is actually a MyException
System.out.println("Caught a RuntimeException");
}
Thus, inheritance allows using custom exceptions as RuntimeException and casting them to this type.