面试题:Java中无需继承Exception/RuntimeException创建自定义异常的可行方法?
extends keyword? Great question! Let’s break this down clearly, since this is almost always asked in the context of Java (the most common language with this structured exception system):
Core Conclusion
In Java, you cannot create a custom exception class (either checked or unchecked) without indirectly or directly extending the Throwable class — which requires using the extends keyword. Here’s why this is non-negotiable:
The Java language and JVM are built to only recognize Throwable and its subclasses as valid types that can be thrown with the throw statement. Any class that doesn’t inherit from Throwable will trigger a compiler error if you try to throw it, and the JVM won’t treat it as an exception during runtime.
Breakdown for Checked vs. Unchecked Exceptions
Let’s dive deeper into both exception categories:
- Checked Exceptions: To make a custom checked exception, your class must extend
Exception(or a subclass ofExceptionthat isn’t aRuntimeException). There’s no way around usingextendshere — checked exceptions are explicitly defined asExceptionsubclasses that aren’t marked as unchecked. - Unchecked Exceptions: For custom unchecked exceptions, you need to extend
RuntimeException(or one of its subclasses). Again,extendsis mandatory. While you could technically extendError(anotherThrowablesubclass),Erroris reserved for system-level failures (likeOutOfMemoryError) and should never be used for application-specific custom exceptions.
Are there any workarounds?
You might think of ways to mimic custom exceptions without creating a new class, but these don’t count as true custom exception types:
- Reusing built-in exceptions with custom messages:
throw new RuntimeException("My specific error message")orthrow new IOException("Custom I/O failure"). This just repurposes existing exception classes with your own text — it doesn’t create a unique exception type you can catch specifically. - Wrapping a custom object inside a standard exception:
throw new Exception(new MyCustomErrorDetails()). This attaches your custom data to a generic exception, but you still can’t catch it withcatch (MyCustomErrorDetails e).
If you want a truly custom exception (one that you can target specifically in catch blocks), you have to extend the Throwable hierarchy using the extends keyword.
内容的提问来源于stack exchange,提问作者surya prakash

