|
|
Flow Control and Exception Handling - Exception Handling
- methods must declare which checked exceptions they may throw in their throws clause
public void methodName throws Exception1, Exception2,()
- you do not have to include any checked exception which will be caught and handled within the method
- a method can throw multiple exceptions
- a method can only throw exceptions that have been declared in the throws clause
- an overriding method cannot throw any checked exceptions which are not part of the original methods throws clause
- the throws clause must also include any possible exceptions that can be thrown by the method
- if you invoke a method that has a checked exception in its throws clause you can
- catch and handle the exception
- catch it and throw one of the exceptions listed in the method throws clause
- declare the exception in your throws clause
- a method which does not have a throws clause may still throw unchecked exceptions or errors
- these exceptions and errors can occur at any time, in any code
Standard Unchecked Exceptions:
ArithmeticException IllegalTrheadStateException
ArrayStoreException IndexOutOfBoundsException
ClassCastException MissingResourceException
EmptyStackException NegativeArraySizeException
IllegalArgumentException NoSuchElementException
IllegalMonitorStateException NullPointerException
IllegalStateException NumberFormatException
SecurityException
Standard Unchecked Errors:
AbstractMethodError NoSuchFieldError
ClassFormatError NoSuchMethodError
ExceptionInInitializerError OutOfMemoryError
IllegalAccessError StackOverflowError
IncompatibleClassChangeError ThreadDeath
InstantiationError UnknownError
InternalError UnsatisfiedLinkError
LinkageError VerifyError
NoClassDefFoundError VirtualMachineError
- Static initializers, instance initializers, and class or variable initializers must not produce any checked exceptions
- exceptions are thrown using the throw statement
throw Expression;
throw new ExampleException();
- or by invoking a method that throws an exception
- the expression must be an instance of a Throwable object ie the exception class must implement Throwable
|