I am experimenting with exceptions and i want to ask when it is possible to handle multiple exceptions in one handler and when it is not?
For example i wrote the following code which combines two exceptions (FileNotFoundException OutOfMemoryError) and the program runs properly without any error. Al thought the handling is not so relevant with the functionality of the code i chose them just to see when i can combine multiple exceptions in on handler :
import java.io.FileNotFoundException; import java.lang.OutOfMemoryError; public class exceptionTest { public static void main(String[] args) throws Exception { int help = 5; try { foo(help); } catch (FileNotFoundException | OutOfMemoryError e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static boolean foo(int var) throws Exception { if (var > 6) throw new Exception("You variable bigger than 6"); else return true; } } But when i choose different type of exceptions the compiler gives me error . For example when i choose IOException and Exception i have the error the exception is already handled " :
import java.io.IOException; import java.lang.Exception; public class exceptionTest { public static void main(String[] args) throws Exception { int help = 5; try { foo(help); } catch (IOException | Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static boolean foo(int var) throws Exception { if (var > 6) throw new Exception("You variable bigger than 6"); else return true; } } So why is this happening ? Why in one occasion i can use multiple exception in handler and in the other not ? Thank you in advance.
IOException?OutOfMemoryErrorbelongs in thejava.lang.Errorhierarchy. Different thanjava.lang.Exception. Take a look at the different classes: IOException & OutOfMemoryErrorThrowable.