Java Reference
In-Depth Information
} catch (IOException e) {
System.out.println("There was an IOException "+e);
} catch (ClassNotFoundException e) {
System.out.println("There was a ClassCastException
"+e);
}
Solution 2
If your application has the tendency to throw multiple exceptions within a single block,
then a vertical bar operator ( | ) can be utilized for handling each of the exceptions in
the same manner. In the following example, the catch clause specifies multiple ex-
ception types separated with a vertical bar ( | ) to handle each of the exceptions in the
same manner.
try {
Class<?> stringClass
= Class.forName("java.lang.String");
FileInputStream in = new
FileInputStream("myFile.log") ;
// Can throw IOException
in.read();
} catch (IOException | ClassNotFoundException e) {
System.out.println("An exception of type
"+e.getClass()+" was thrown! "+e);
}
How It Works
There are a couple of different ways to handle situations where multiple exceptions
may be thrown. You can specify separate catch clauses to handle each of the excep-
tions in a different way. To handle each of the exceptions in the same manner, you can
utilize a single catch clause and specify each exception separated with a vertical bar
operator.
Search WWH ::




Custom Search