Custom Exceptions
By inheriting from Exception or its subclasses, you can create custom exception types. Custom exceptions can carry additional fields, such as error codes, field names, etc., providing richer context information for error handling.
When defining custom exceptions, you need to:
- Use
open classdeclaration (allows further inheritance) - Call the parent constructor
super(message)to pass the error message - Override the
getClassName()method to return the exception name
The code on the right defines two exceptions: ValidationError carries a field name, and NetworkError carries a status code. You can access this additional information in catch blocks.
Note
You cannot inherit from the
Error class. Error represents system-level errors that programs should not throw or catch.Modify the code to add a value field to ValidationError to store the invalid value.