Introduction Flashcards

1
Q

What is the utility of a try statement ?

A

The utility of a try statement is to separate the logic that might
throw an exception from the logic that handles that exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Describe how the try block handle exceptions ?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give a characteristic of the catch block !

A

If an exception is thrown inside the try block that is not listed
in a catch block, the catch block doesn’t get run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give an example of the try catch block that illustrates the example of the girl falling !

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give how the exam is going to trick you when it comes to try statements !

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the finality of a try statement ?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly