Exceptions and Errors
- Exceptions and Errors both are subclasses of
Throwable class.
Throwable:
classDiagram
Throwable <|-- Exception
Throwable <|-- Error
Exception <|-- IOException
Exception <|-- RuntimeException
RuntimeException <|-- NullPointerException
Error <|-- IOError
Error <|-- VirtualMachineError
VirtualMachineError <|-- OutofMemoryError
VirtualMachineError <|-- StackOverflowError
Types
- Errors
- Exceptions
- Checked (compile time) — Code will not compile at all
- Unchecked (runtime)
Error
- indicates serious problems that a reasonable application should not try to catch
- Most such errors are abnormal conditions like lack of system resources
- It indicates serious problem in app
- It should not be caught or handled
Error:
IOError — Serious issue with underlying filesystem
AssertionError —
VirtualMachineError — indicates JVM running out of resources
InternalError
UnknownError
OutOfMemoryError
StackOverflowError
- It is possible to throw error but it is not recommended
try {
throw new Error("something is wrong");
} catch (Error e) {
System.out.println(e.getMessage()); // something is wrong
}
Exception
- Exceptions are the problems which can occur at runtime and compile time.
- It mainly occurs in the code written by the developers.
Checked
- They are checked at compile time
- All exceptions which inherit from
Exception class except RuntimeException are checked
Exception:
IOException
ApplicationException
SQLException
CloneNotSupportedException
DataFormatException
Unchecked
- They occur at runtime
- All Exceptions which inherit
RuntimeException are unchecked
Exception:
RuntimeException:
NullPointerException — calling an action on null object
ArithmeticException — invalid math operation like diving by zero
DateTimeException — problem while calculating a date-time.
UnsupportedOperationException — requested operation is not supported
IndexOutOfBoundsException — index is out of range.
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
IllegalArgumentException — passed an inappropriate argument.
NumberFormatException — failed to convert character to number
Defining Custom Exceptions
- For Checked Exceptions you can extend
Exception class
- For Unchecked Exceptions you can extend
RuntimeException class (which internally extends Exception)
public class FibonacciInputException extends Exception {
public FibonacciInputException(String message) {
super(message);
}
}
Chained Exception