0
0
Javaprogramming~10 mins

Finally block in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to ensure the block always runs after try.

Java
try {
    System.out.println("Try block");
} [1] {
    System.out.println("This always runs");
}
Drag options to blanks, or click blank then click option'
Afinally
Bfinal
Ccatch
Dcatch(Exception e)
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using catch without specifying exception
Using final instead of finally
2fill in blank
medium

Complete the code to catch an exception and still run the final block.

Java
try {
    int a = 5 / 0;
} [1] (ArithmeticException e) {
    System.out.println("Caught division by zero");
} finally {
    System.out.println("Always runs");
}
Drag options to blanks, or click blank then click option'
AcatchError
Bcatch
Ccatch(Exception e)
Dfinal
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using final instead of finally
Writing catch without parentheses
3fill in blank
hard

Fix the error in the finally block declaration.

Java
try {
    System.out.println("Try block");
} catch(Exception e) {
    System.out.println("Exception caught");
} [1] {
    System.out.println("This always runs");
}
Drag options to blanks, or click blank then click option'
Afinal
Bfinalize
Ccatch
Dfinally
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using final instead of finally
Using catch instead of finally
4fill in blank
hard

Fill both blanks to complete the try-catch-finally structure.

Java
try {
    int[] arr = new int[2];
    System.out.println(arr[[1]]);
} [2] (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index error caught");
} finally {
    System.out.println("Cleanup done");
}
Drag options to blanks, or click blank then click option'
A3
Bcatch
C2
Dfinal
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using index 2 which is also out of bounds but less clear
Using final instead of catch
5fill in blank
hard

Fill all three blanks to create a try-catch-finally that handles null pointer exception.

Java
String s = null;
try {
    System.out.println(s.[1]());
} [2] (NullPointerException e) {
    System.out.println("Null pointer caught");
} [3] {
    System.out.println("Always runs");
}
Drag options to blanks, or click blank then click option'
Alength
Bcatch
Cfinally
Dsize
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using size() which is not a String method
Using final instead of finally