Concept
How do you create a custom exception in Java?
ComputerScienceOne / Creating Custom Exceptions
"To create your own exceptions, you need to create a new class to represent the exception and make it extend RuntimeException by using the keyword extends. This makes your exception a subclass or subtype of the RuntimeException. This is a concept known as inheritance in OOP. Consider the example in the previous chapter of computing the roots of a quadratic polynomial. One possible error situation is when the roots are complex numbers. We could define a new Java class as follows.\n\npublic class ComplexRootException extends RuntimeException {\n\n/**\n\n* Constructor that takes an error message\n\n*/\n\npublic ComplexRootException(String errorMessage) {\n\nsuper(errorMessage);\n\n}\n\n}"
Related Ideas
- How do you create a custom exception in Java?ComputerScienceOne · Throwing Exceptions
- How can you manually throw a generic RuntimeException?ComputerScienceOne · Throwing Exceptions
- What is a checked exception in Java?ComputerScienceOne · Checked Exceptions
- How do you catch and handle an exception in Java?ComputerScienceOne · Catching Exceptions
- Why should the most specific exception types be caught before the most general types?ComputerScienceOne · Creating Custom Exceptions
- How can Java handle different exception types with multiple catch blocks?ComputerScienceOne · Catching Exceptions
- Why should the most specific exception types be caught before general ones?ComputerScienceOne · Throwing Exceptions
- How can you create and handle custom exception classes in PHP?ComputerScienceOne · Creating Custom Exceptions