Commit 4b94fe2
committed
feat(generic-exceptions): add example for throwing generic exceptions using reflection
WHAT:
- Implemented a generic utility method `<T extends Exception> void throwGenericException(Class<T>)`
that dynamically throws exceptions of any provided type.
- Demonstrated usage in `Main4` where `IllegalArgumentException` is instantiated and thrown.
WHY:
- Java does not allow truly generic exception classes due to type erasure.
- However, developers often want reusable utility methods to throw exceptions of different types.
- This example demonstrates how reflection can be used to instantiate and throw exceptions
while preserving type safety via generics.
HOW:
- Method `throwGenericException(Class<T> exceptionClass)`:
- Uses reflection to find a constructor that accepts a `String` parameter.
- Creates a new instance of the provided exception type with a fixed message (`"Generic Exception"`).
- If reflection fails, catches the checked `Exception` and rethrows it as the generic type `T`.
- In `main()`:
- Calls `throwGenericException(IllegalArgumentException.class)`.
- The thrown exception is caught as `IllegalArgumentException`, and its message is printed.
BENEFITS:
- Demonstrates flexibility of combining generics and reflection for reusable exception handling.
- Useful in frameworks or libraries where exception types need to be determined dynamically
(e.g., validation libraries, generic service layers).
LIMITATIONS:
- Relies on reflection → slower performance and possible runtime errors if the exception type
doesn’t have a matching constructor.
- Type safety is partially bypassed with unchecked casting `(T) e`.
- Best suited for utility methods, not performance-critical code.
REAL-WORLD USE CASES:
- Validation frameworks that throw domain-specific exceptions (`ValidationException`, `BusinessException`)
based on context.
- Generic APIs where exception type is configurable by the caller.
- Simplifying boilerplate code by centralizing exception throwing in a generic utility.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 8b45404 commit 4b94fe2
1 file changed
+21
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
0 commit comments