0
0
Javaprogramming~10 mins

Why exception handling is required in Java - Test Your Understanding

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

Complete the code to catch an exception when dividing by zero.

Java
try {
    int result = 10 / [1];
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
}
Drag options to blanks, or click blank then click option'
A10
B1
C2
D0
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a non-zero number which does not cause an exception.
2fill in blank
medium

Complete the code to handle a possible null pointer exception.

Java
String text = null;
try {
    int length = text.[1]();
} catch (NullPointerException e) {
    System.out.println("Text is null.");
}
Drag options to blanks, or click blank then click option'
Alength()
BcharAt
Clength
DtoString
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using length without parentheses which is invalid for String.
3fill in blank
hard

Fix the error in the code to properly catch exceptions.

Java
try {
    int[] arr = new int[3];
    int value = arr[5];
} catch ([1] e) {
    System.out.println("Index out of bounds.");
}
Drag options to blanks, or click blank then click option'
AArithmeticException
BNullPointerException
CArrayIndexOutOfBoundsException
DIOException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Catching the wrong exception type that does not match the error.
4fill in blank
hard

Fill both blanks to create a try-catch block that handles file reading exceptions.

Java
try {
    FileReader file = new FileReader("test.txt");
    BufferedReader reader = new BufferedReader(file);
    String line = reader.readLine();
} catch ([1] e) {
    System.out.println("File not found.");
} catch ([2] e) {
    System.out.println("IO error occurred.");
}
Drag options to blanks, or click blank then click option'
AFileNotFoundException
BNullPointerException
CIOException
DArithmeticException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Swapping the order of exceptions or using unrelated exceptions.
5fill in blank
hard

Fill all three blanks to create a method that throws and catches a custom exception.

Java
class MyException extends Exception {}

public class Test {
    public static void check(int num) throws [1] {
        if (num < 0) {
            throw new [2]();
        }
    }

    public static void main(String[] args) {
        try {
            check(-1);
        } catch ([3] e) {
            System.out.println("Custom exception caught.");
        }
    }
}
Drag options to blanks, or click blank then click option'
AMyException
DException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using Exception instead of the custom exception class.