O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mind the Catch Order

Unlike Java, we have to be mindful of the order in which we place the catch blocks. The Java compiler is more vigilant than Scala in this area. When attempting to handle exceptions, Java watches over the order in which we place multiple catch blocks. The following example will give us a compilation error:

ExceptionHandling/JavaCatchOrder.java
 
//Java code—will not compile due to incorrect catch order
 
 
public​ ​class​ JavaCatchOrder {
 
public​ ​void​ catchOrderExample() {
 
try​ {
 
String​ str = ​"hello"​;
 
System​.out.println(str.charAt(31));
 
}
 
catch​(Exception ex) { ​System​.out.println(​"Exception caught"​); }
 
catch​(StringIndexOutOfBoundsException ex) { ​//ERROR
 
System​.out.println(​"Invalid Index" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required