0
0
Javaprogramming~10 mins

Multiple catch blocks 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 catch an ArithmeticException.

Java
try {
    int result = 10 / 0;
} catch ([1] e) {
    System.out.println("Cannot divide by zero.");
}
Drag options to blanks, or click blank then click option'
ANullPointerException
BIOException
CArithmeticException
DArrayIndexOutOfBoundsException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using IOException instead of ArithmeticException.
Catching NullPointerException which is unrelated here.
2fill in blank
medium

Complete the code to catch a NullPointerException.

Java
String text = null;
try {
    int length = text.length();
} catch ([1] e) {
    System.out.println("Text is null.");
}
Drag options to blanks, or click blank then click option'
ANullPointerException
BIOException
CArithmeticException
DNumberFormatException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Catching IOException which is unrelated.
Using ArithmeticException which is for math errors.
3fill in blank
hard

Fix the error in the catch block to handle NumberFormatException.

Java
try {
    int num = Integer.parseInt("abc");
} catch ([1] e) {
    System.out.println("Invalid number format.");
}
Drag options to blanks, or click blank then click option'
AIOException
BArithmeticException
CNullPointerException
DNumberFormatException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Catching IOException which is unrelated here.
Using ArithmeticException which is for math errors.
4fill in blank
hard

Fill both blanks to catch ArithmeticException and NullPointerException separately.

Java
try {
    int result = 10 / 0;
    String text = null;
    int length = text.length();
} catch ([1] e) {
    System.out.println("Arithmetic error occurred.");
} catch ([2] e) {
    System.out.println("Null pointer error occurred.");
}
Drag options to blanks, or click blank then click option'
AArithmeticException
BIOException
CNullPointerException
DNumberFormatException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Swapping the exception types in the catch blocks.
Using unrelated exceptions like IOException.
5fill in blank
hard

Fill all three blanks to catch NumberFormatException, ArithmeticException, and NullPointerException in separate catch blocks.

Java
try {
    int num = Integer.parseInt("abc");
    int result = 10 / 0;
    String text = null;
    int length = text.length();
} catch ([1] e) {
    System.out.println("Number format error.");
} catch ([2] e) {
    System.out.println("Arithmetic error.");
} catch ([3] e) {
    System.out.println("Null pointer error.");
}
Drag options to blanks, or click blank then click option'
AIOException
BArithmeticException
CNullPointerException
DNumberFormatException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Mixing up the order of exceptions in catch blocks.
Using IOException which is unrelated.