Week 5 Flashcards
What are the two types of exceptions?
Check and unchecked
What are checked exceptions?
Exceptions that have to be caught
What are unchecked exceptions?
Exceptions that don’t have to be caught e.g. ArrayIndexOutOfBoundsException
How do you make your own exception?
You use extend to extend an existing exception, e.g. public class MyException extends RuntimeException{ }
How do you catch exceptions?
use try catch and finally blocks
What’s an example of a try, catch, finally block?
import java.util.Random; public class PracticeFromLectures { public static void main(String[] args) { int[] x= new int[10]; //int array with length 10 Random r = new Random(); try{ int pos = r.nextInt(20); System.out.println(pos); System.out.println(x[pos]); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Too big!"); } finally { System.out.println("This prints anyway"); } } }
What’s an example of a checked exception?
FileNotFoundException - if the named file doesn’t exist or it’s a directory (or not a file) it’ll throw an exception
How do we close FileReader objects?
in the finally block, we can have try and catch. In the try statement, we can close the FileReader.
What is the hierarchy of java.io.FileNotFoundException? i.e. where does it inherit from?
java. io.FileNotFoundException inherits from:
java. io.IOException, which inherits from:
java. lang.Exception, which inherits from:
java. lang.Throwable, which inherits from:
java. lang.Object
You can catch a FileNotFoundException as Throwable, Exception and IOException. As you go up, it gets more abstract
How do you delegate catches?
You can use the word throws, e.g.
public void myMethod(String a) throws IOException, ArrayIndexOutOfBoundsException { }
If you don’t want to deal with the exception, you can delegate it up to whatever called your method
What does the FileReader do?
It allows us to read individual characters
How do you use String.split method?
Define a new String:
String line = “Katie Ghaemi, 27”;
Then if we want to split by comma, we will store all of the values in a String array:
String[] tokens = line.split(“,”);