Point Out The Mistakes
public class Mistakes {
public static void main(String[] args) {
try {
throwException();
} catch (MissingResourceException e){
} catch (InputMismatchException e | FileNotFoundException e){
} catch (ParseException | ArrayIndexOutOfBoundsException e){
} catch (MissingResourceException | IllegalArgumentException e){
} catch (Throwable e){
} catch (IOException e){
}
}
private static void throwException() throws DateTimeException, IOException{
// ...
}
}
- Line six tries to use multi-catch but fails to use the right syntax
- Line 9 and 10 are in the wrong order
- The MissingResourceException on line 8 has already been caught
- The checked ParseException on line 7 is never thrown in the try block
Suppressed Exceptions
Suppressed exceptions occur when an exception is thrown in the try with clause:
package Exceptions;
public class Suppressed {
static class Tools implements AutoCloseable{
@Override
public void close() throws IllegalArgumentException {
throw new IllegalArgumentException("OMG what did I do");
}
}
public static void main(String[] args) {
try(Tools tools = new Tools()){
throw new RuntimeException("Oh No");
} catch (IllegalArgumentException e){
System.out.println("Exception occured: " + e.getMessage());
}
}
}
Output:
Exception in thread "main" java.lang.RuntimeException: Oh No at Exceptions.Suppressed.main(Suppressed.java:13) Suppressed: java.lang.IllegalArgumentException: OMG what did I do at Exceptions.Suppressed$Tools.close(Suppressed.java:7) at Exceptions.Suppressed.main(Suppressed.java:14)
Good 2 Know
- Checked exceptions cannot be caught when not thrown in the corresponding try block
- close() may not throw an Exception in a class that implements Closeable
- Assertions can be turned on with the -ea argument