Commit 8b45404
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
1 file changed
+29
-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 | + | |
| 28 | + | |
| 29 | + | |
0 commit comments