Skip to content

Commit 8b45404

Browse files
committed
feat(generic-exceptions): add custom exception with error codes (non-generic example)
WHAT: - Implemented a `CustomException2` class extending `Exception` to demonstrate how to enrich exceptions with additional contextual data (like error codes). - Added `Main3` class with example usage where `throwException()` throws the custom exception, and the `main` method catches and prints the error code. WHY: - Standard Java exceptions often carry only a message, making it hard to attach structured metadata like error codes or identifiers. - By extending `Exception` and adding fields (e.g., `errorCode`), we can provide more diagnostic information without relying on generics (since generic exceptions are restricted due to type erasure). HOW: - `CustomException2` includes: - `String message`: passed to `super(message)` for compatibility with existing exception handling. - `int errorCode`: a custom field to store a numeric identifier for the error. - `getErrorCode()`: accessor to retrieve the code during exception handling. - In `Main3`: - `throwException()` method always throws a `CustomException2` with error code `1001`. - `main` catches the exception, extracts the error code, and prints it. BENEFITS: - Developers can differentiate between exceptions not only by type or message but also by structured fields (like error codes). - Facilitates better logging, debugging, and mapping to user-friendly error responses in applications. REAL-WORLD USE CASES: - Banking/Finance: Attach transaction IDs or error codes for failed operations. - REST APIs: Use error codes to map to HTTP status codes and provide consistent client responses. - Enterprise apps: Internal error catalog where each error is assigned a unique code for support teams. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 7c2a07a commit 8b45404

File tree

1 file changed

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

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package GenericExceptions;
2+
3+
// Custom Exception without generics
4+
class CustomException2 extends Exception {
5+
private final int errorCode;
6+
7+
public CustomException2(String message, int errorCode) {
8+
super(message);
9+
this.errorCode = errorCode;
10+
}
11+
12+
public int getErrorCode() {
13+
return errorCode;
14+
}
15+
}
16+
17+
public class Main3 {
18+
public static void main(String[] args) {
19+
try {
20+
throwException();
21+
} catch (CustomException2 e) {
22+
System.out.println("Caught an exception with error code: " + e.getErrorCode());
23+
}
24+
}
25+
26+
public static void throwException() throws CustomException2 {
27+
throw new CustomException2("Something went wrong", 1001);
28+
}
29+
}

0 commit comments

Comments
 (0)