Skip to content

Commit 7c2a07a

Browse files
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

File tree

1 file changed

+27
-0
lines changed
  • Section24JavaGenerics/src/GenericExceptions

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package GenericExceptions;
2+
3+
/*
4+
class DetailedException<T> extends Exception {
5+
private T details;
6+
7+
public DetailedException(String message, T details) {
8+
super(message);
9+
this.details = details;
10+
}
11+
12+
public T getDetails() {
13+
return details;
14+
}
15+
}
16+
17+
public class Main2 {
18+
public static void main(String[] args) {
19+
try {
20+
throw new DetailedException<Integer>("An error occurred", 404);
21+
} catch (DetailedException<Integer> e) {
22+
System.out.println(e.getMessage());
23+
System.out.println(e.getDetails());
24+
}
25+
}
26+
}
27+
*/

0 commit comments

Comments
 (0)