Java Features Java 5 Java 7 Java 8 |
Java 7 features Binary literals | Strings in switch statements | Catching multiple exceptions | Try with resources | Type inference | Underscores in numeric literals | By date |
In the following example we apply catching multiple exception types, which is a new feature in JSE7, In the earlier Java versions you could catch each exception type in a separate block, but in Java 7 you can catch multiple types of exceptions in one block. For more info click here to read Oracle’s explanation.
Example 1: Catching two exception types
What is the output of the following code?
public class HandlingMultiException { public static void main(String args[]) { try { String[] arrCountries = new String[7]; arrCountries[6].substring(3); } // catching two exception types in one block catch(NullPointerException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }
Author: Sar Maroof
Answer explanation
- In the previous code we created an array with length of 7. If you try to access an element of the array greater than its length, that would result in ArrayIndexOutOfBoundsException. For example arrCountries[8].substring(3); would result in ArrayIndexOutOfBoundsException.
- If you try to access a substring of any of the elements, that would result in NullPointerException. That is because the elements of the array are not initialized.
The statement arrCountries[6].substring(3); results in NullPointerException.
The correct answer is: null.
In the earlier Java versions we used more lines of code to write the same program. Here below how the previous code looks like in older Java versions.
public class HandlingException { public static void main(String args[]) { try { String[] arrCountries = new String[7]; arrCountries[6].substring(3); } catch(NullPointerException e) { System.out.println(e.getMessage()); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }
Suggested Articles
![]() ![]() ![]() |