Introduction Flashcards
What is the utility of a try statement ?
The utility of a try statement is to separate the logic that might
throw an exception from the logic that handles that exception
Describe how the try block handle exceptions ?
The code inside the try block runs normally.
If any of the statements throw an exception that can be caught by the exception type listed in the catch block, the try block stops running and execution goes to the catch statement.
If none of the statements in the try block throw an exception that can be caught, the catch clause is not run.
Give a characteristic of the catch block !
If an exception is thrown inside the try block that is not listed
in a catch block, the catch block doesn’t get run.
Give an example of the try catch block that illustrates the example of the girl falling !
3: void explore() {
4: try {
5: fall();
6: System.out.println(“never get here”);
7: } catch (RuntimeException e) {
8: getUp();
9: }
10: seeAnimals();
11: }
12: void fall() { throw new RuntimeException(); }
First, line 5 calls the fall() method.
Line 12 throws an exception.
This means Java jumps straight to the catch block, skipping line 6.
The girl gets up on line 8. Now the try statement is over and execution proceeds normally with line 10
Give how the exam is going to trick you when it comes to try statements !
Now let’s look at some invalid try statements that the exam might try to trick you with
try // DOES NOT COMPILE
fall();
catch (Exception e)
System.out.println(“get up”);
//Braces are missing
try statements are like methods in that the curly braces are required even if there is only one statement inside the code blocks
the try clause can never be used without a catch or finally blocks and therefore can never be used as a stadalone statement, so the following statement does not compile :
try { // DOES NOT COMPILE
fall();
}
// This code doesn’t compile because the try block doesn’t have anything after it.
What is the finality of a try statement ?
The primary purpose of a try statement is to allow for exception handling by redirecting control to the appropriate catch block when an exception occurs