Commit 7c2a07a
committed
docs(exceptions): illustrate use of generics inside exception fields (not in class definition)
WHAT:
- Added example `DetailedException<T>` class extending `Exception`.
- The generic type `T` is used for a field (`details`) rather than making the entire exception class generic.
- Demonstrated usage in `Main2` by throwing and catching a `DetailedException<Integer>`.
WHY:
- Java does not allow fully generic custom exceptions (`class MyException<T> extends Exception`)
due to type erasure and runtime type resolution of exceptions.
- However, generics can still be applied to *fields or methods* inside exception classes.
- This pattern lets developers attach strongly-typed metadata (like error codes, invalid values,
or additional context) to exceptions.
KEY POINTS:
1. The exception class itself is concrete (extends `Exception`) and safe to use in try/catch.
2. Generic field `details` provides flexibility for attaching typed context.
3. Example shows usage with `Integer` as error details (`404`).
REAL-WORLD USAGE:
- Embed diagnostic data inside exceptions (e.g., IDs, enums, or error payloads).
- Common in frameworks or APIs where exceptions need to carry contextual information
without losing type safety.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent de96044 commit 7c2a07a
1 file changed
+27
-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 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
0 commit comments