Things to Know Part 6
Exception:
java.lang.Object
↑
java.lang.Throwable
↗ ↖
java.lang.Exception java.lang.Error
↑
java.lang.RuntimeException
Checked:
-checked exceptions come from the Exception class and all subclasses that DO NOT extend from the RuntimeException class.
-programs are required to handle checked exceptions
FileNotFoundException - thrown programmatically
subclass of IOException
IOException - thrown programmatically
Unchecked:
-unchecked exceptions come from the RuntimeException class and all of its subclasses.
-programs are not required to handle unchecked exceptions
-can be thrown by programmer or JVM
ArithmeticException - thrown by JVM
ArrayIndexOutOfBoundsException - thrown by JVM
ClassCastException - thrown by JVM
IllegalArgumentException - thrown by JVM
NullPointerException - thrown by JVM
NumberFormatException - thrown by programmer
Errors:
-extend from Error class
ExceptionInInitializerError - thrown by JVM
StackOverflowError - thrown by JVM
NoClassDefFoundError - thrown by JVM
Try Statements:
try{ /*must have one or more of the following */}
catch(RuntimeException e) { /* can be any subclass of Exception */}
catch(Exception e) { /* can have multiple catches but only one will run. */
/*Must be higher or equal class level of previous catch. */ }
finally { /*optional. runs after try or catch. */
/* can only have one */ }
Throwing Exceptions:
-use throw keyword and then but an Exception object.
throw new Exception();
or
Exception e = new Exception();
throw e;
takes optional parameter of string in constructor
throw new Exception("Main Class, runStuff(int) method");
Methods Declaring Exceptions
-use throws keyword to indicate that anyone calling this method may potentially need to handle exception.
public void someMethod() throws IllegalArgumentException {
//code for method goes here
//method DOES NOT have to throw an IllegalArgumentException
//but it would do so like this:
throw new IllegalArgumentException();
}
//anywhere this method gets called, it must either be surrounded by a try/catch
//block, or the method it gets called from
//must also throw an IllegalArgumentException.
EXAMPLE:
try {
someMethod();
}catch(IllegalArgumentException e){
//can also take any superclass of IllegalArgumentException
}
source:
Boyarsky, Jeanne, and Scott Selikoff. OCA Oracle Certified Associate. Study Guide. John Wiley & Sons, 2015.