0
0
Javaprogramming~10 mins

Try–catch 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 catch an exception.

Java
try {
    int result = 10 / 0;
} catch ([1] e) {
    System.out.println("Error occurred");
}
Drag options to blanks, or click blank then click option'
Aint
BException
CString
Dvoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using a data type like int or String instead of an exception type.
Leaving the catch parentheses empty.
2fill in blank
medium

Complete the code to print the exception message.

Java
try {
    int[] arr = new int[2];
    System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println(e.[1]());
}
Drag options to blanks, or click blank then click option'
AtoString
BprintStackTrace
CgetMessage
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using printStackTrace() which prints the whole trace instead of just the message.
Using length which is not a method of exceptions.
3fill in blank
hard

Fix the error in the catch block declaration.

Java
try {
    int a = Integer.parseInt("abc");
} catch ([1] e) {
    System.out.println("Invalid number format");
}
Drag options to blanks, or click blank then click option'
ANumberFormatException
BNullPointerException
CIOException
DArithmeticException
Attempts:
3 left
💡 Hint
Common Mistakes
Using unrelated exceptions like IOException or ArithmeticException.
Not catching the specific exception thrown.
4fill in blank
hard

Fill both blanks to catch an exception and print its message.

Java
try {
    String s = null;
    System.out.println(s.length());
} catch ([1] e) {
    System.out.println(e.[2]());
}
Drag options to blanks, or click blank then click option'
ANullPointerException
BgetMessage
CprintStackTrace
DIOException
Attempts:
3 left
💡 Hint
Common Mistakes
Using IOException which is unrelated.
Using printStackTrace instead of getMessage.
5fill in blank
hard

Fill all three blanks to catch an exception, print its message, and execute code after try-catch.

Java
try {
    int[] nums = {1, 2, 3};
    System.out.println(nums[[1]]);
} catch ([2] e) {
    System.out.println(e.[3]());
}
System.out.println("Program continues");
Drag options to blanks, or click blank then click option'
A5
BArrayIndexOutOfBoundsException
CgetMessage
DNullPointerException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a valid index like 2 which does not cause an exception.
Using NullPointerException which is unrelated here.
Using printStackTrace instead of getMessage.