What is the difference between these Java Exceptions? - java

I have two different exceptions, one is named "e" and the other "e1". What I do not understand is:
What is the difference between "e" and "e1"?
Example 1:
catch(ClassNotFoundException | SQLException e) {
System.out.println(e);
...
Example 2:
catch (Exception e1) {
label.setText("SQL Error");
System.err.println(e1);
...

The variable names themselves do not have any relevance.
But you can not have 2 variables with the same name in the same try-catch block.
In the first case 'e' is can be of type ClassNotFoundException or SQLException,
Depending on what exception was thrown.

In the first case:
catch(ClassNotFoundException | SQLException e){
System.out.println(e);
Only exceptions of ClassNotFoundException or SQLException (or their subclasses) will be caught.
In the second case:
catch (Exception e1) {
label.setText("SQL Error");
System.err.println(e1);
Any Exception (or subclass of) will be caught.

Related

Why is it allowed to catch subtype of a thrown exception in Java

I read in a Java book, that "Java will not allow you to declare a catch block for a checked exception type that cannot potentially be thrown by the try class body".
That makes sense so far.
But now I am asking myself why this code does compile:
try {
throw new Exception();
} catch (IOException e) {
} catch (Exception e) {
}
Java allows me to catch the IOException, but obviously it will never be thrown by the try-block.
Doesn't this example break the rule described in the Java book?
Java allows me to catch the IOException, but obviously it will never
be thrown by the try-block.
Because Exception is more general than IOException so the compiler understand that Exception can also be IOException.
Here is a contre example of what will happen if you try NumberFormatException instead of Exception
try {
throw new NumberFormatException();
} catch (IOException e) { // fail
} catch (Exception e) {
}
It fail because NumberFormatException is not general than IOException.
It is obvious to a programmer that reads this code, but i guess the compiler will deal with the throw statement the same way it would deal with a call to a method declared as throwing Exception, and in this case, the thrown exception could very well be an IOException.

catching exception in catch block

What is difference between
try {
...
} catch (Nullpointerexception e) { ... }
} catch (Exception e) { ... }
and
try {
...
} catch (Exception e) { ... }
Suppose I have a NullPointerException, which one is best? And why?
Q: What is difference between catch(Nullpointerexception e) and catch(Exception e)?
A: The one former is specific, the latter is general.
There are times when you want to handle specific classes of exceptions (like "NullPointerException") one way, but different classes of exception (like "IOException") differently.
In general, you should should choose to handle the "narrowest" exception possible, rather than "handle everything".
Another significant difference between "NullPointerException" (and "ArrayIndexOutOfBound") vs. many other exceptions is that NullPointerException is an unchecked exception.
Note, too, that in Java 7 you can how catch multiple different exceptions in the same catch block:
Catching Multiple Exceptions in Java 7
// Pre-Java 7 code:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException e) {
logger.log(e);
} catch(IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
But now...
// Java 7 and higher
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
You should use the second option if the code to handle Exception is always the same, and the first one if you want different behaviours for different Exceptions.
In any case, is very rare to need a catch clause for NullPointerExceptions, because you can simply avoid them with a null check in your code (you'll really need a catch clause only if the NullPointerException is generated in code you cannot control, for example in the internals of a library).
Starting from Java 7, you can even do:
try {
...
} catch (NullPointerException | AnotherException e) {
...
}
to avoid replicating the same body for different Exception classes.
Prior to Java 7, you have to include the Exception handling code in a method and call if from multiple catch clauses to avoid its replication.

order in multi-catch exception handler

I know since Java 7 you can use multi-catch but I wonder if the order of exceptions in it matters like in previous versions of java? E.g I put in Exception and then SQLException and IOException ?
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(Exception | SQLException | IOException e) {
logger.log(e);
}
Or should I do it this way ?
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
There's no point in a single catch block for catch(Exception | SQLException | IOException e) since Exception already covers its sub-classes IOException and SQLException.
Therefore catch(Exception e) would be enough if you wish the same handling for all of those exception types.
If you want different handling for the more general Exception, your second code snippet makes sense, and here the order of the two catch blocks matters, since you must catch the more specific exception types first.
Yes Order is important, it is from Child to Parent.
Refer this for more such.
The exception variable is implicitly final, therefore we cannot assign
the variable to different value within the catch block. For example,
the following code snippet will give a compile error
} catch (IOException | SQLException ex) {
ex = new SQLException();
}
The compiler will throw this error: multi-catch parameter ex may not be assigned
It is not allowed to specify two or more exceptions of a same
hierarchy in the multi-catch statement. For example, the following
code snippet will give a compile error because the
FileNotFoundException is a subtype of the IOException
} catch (FileNotFoundException | IOException ex) {
LOGGER.log(ex);
}
The compiler will throw this error (no matter the order is): Alternatives in a multi-catch statement cannot be related by subclassing
The Exception class is the supertype of all exceptions, thus we also
cannot write
} catch (IOException | Exception ex) {
LOGGER.log(ex);
}
Multi catch feature is provided in java to remove code duplication in two different hierarchical exceptions. If you are using it for this reason the ordering does not matter. If you are catching parent exception class Exception in multi catch block, then there is no need to add child exception IOException, SQLException classes.
The order matters, because if you try to catch Exception first, and your second catch is for IOException, obviously you'll never hit the second catch. So the order must be from the smallest Exception to the biggest.
The multicatch Exceptiontypes are separated by an 'OR', so no, the order doesn't matter.
You should only use the multicatch if you plan to have all the Exceptiontypes be handled the same way anyway, and if that's the case, the order doesn't matter.
EDIT: indeed, if the types are in a hiërarchical line, only the 'alternative' (in this case the generic Exception) type should be caught.
This has nothing to do with their order, though.
The Exceptions have some hierarchy. Exception e is more objective than others, because of that, it should be last exception that you handle.
There are no comparison between IOException and SQLException, because of that, you can handle them whatever you want.
So, the order should be:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
or
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException e) {
logger.log(e);
} catch(IOException e){
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
or
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(IOException e) {
logger.log(e);
} catch(SQLException e){
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}

Exception Catching Hierarchy Process

I am implementing exception handling in java with multiple exceptions.
Look at the following scenario:
Function f1 throws Exceptions e1, e2, e3 and e4
and Function f2 catches these.
Now I want to catch e1,e2 explicitly by catch(Exception e1 and e2) and the other exceptions should be caught all in the same block by catch(Exception e)
So e1 and e2 are a special case, and others are all general exceptions.
So will the following work?
try{
//some work`
} catch(ExceptionType1 e1) {
//do some special logging
} catch (ExceptionType2 e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}
My question is whether ExceptionType1(e1) will also be caught by Exception e?
The Spec writes:
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:
If that block completes normally, then the try statement completes normally.
If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
Therefore, at most one catch block will be executed.
For that to work you need to have catch blocks with different Exceptions
like NullPointerException NumberFormatException and the general exception will be caught by catch block with Exception parameter since Exception is the super class of all Exceptions
try{
//some work`
} catch(NullPointerException e1) {
//do some special logging
} catch (NumberFormatException e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}
Using your code will catch all Exceptions in catch(Exception e1){...}
The other catch-blocks are unused. If you want to handle different Exception-types on different way you have to give the catch(...) other Exception-types.
Like
try{
}catch(IOException e1){
// Do sth
}
catch(NullPointerException e2){
// Do sth else
}
// and so on...
You cannot have multiple catch blocks with the same class i.e. Exception
If you have multiple Exceptions you need to create a separate class for each one and make your catch block for a specific class
Just be aware the order of your catch block must go from the more specific to the more generic class
e.g.
try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
} catch (Throwable e) {
System.err.println("Caught Throwable: " + e.getMessage());
}
So in the above code if the exception is of FileNotFoundException only the first catch will be executed. Otherwise the catch block with Exception is going to be executed for any instance of Exception class that was not caught in the previous catch blocks
At the end Throwable will catch anything that does not inherent from Exception such as Error

Java reflect API wrapper (damn checked exceptions cluttering)

I have methods that look like this:
public static <U extends Entity<?, ?>> Http<List<U>> getAllFromServerThreadRun(Integer maxResults, Class<U> clazz) {
JsonObject o2 = new JsonObject(); // TODO exception chaos im projekt
// überarbeiten
o2.addProperty("maxResults", maxResults);
String s;
Type t;
try {
U o = clazz.getConstructor().newInstance();
s = (String) clazz.getDeclaredMethod("getControllerName").invoke(o);
t = (Type) clazz.getDeclaredMethod("getListType").invoke(o);
} catch (IllegalArgumentException e) {
ExceptionHandler.handle(e);
} catch (SecurityException e) {
ExceptionHandler.handle(e);
} catch (InstantiationException e) {
ExceptionHandler.handle(e);
} catch (IllegalAccessException e) {
ExceptionHandler.handle(e);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e);
} catch (NoSuchMethodException e) {
ExceptionHandler.handle(e);
}
return new Http<List<U>>(new HttpGet(), s, "getall", t).setParams(o2).queryServer();
}
Maybe 10 of them exist in my project as of now.
I there a alternative Java reflection library that hides these exceptions for me? I don't know what to do with them, and it's just clutter.
I suggest
catch (Exception e) {
ExceptionHandler.handle(e);
}
In java 7, you can catch multiple exception types in each catch:
try {
// reflection stuff
} catch (IllegalArgumentException |
SecurityException |
InstantiationException |
etc e) {
ExceptionHandler.handle(e);
}
I sympathise with you wanting to catch (Exception e) because of the numerous types of exceptions thrown by reflection methods, but doing so carries the danger of jnintentionally catching unchecked Exceptions, like NullPointerException which may mask bugs.
If you're still in java 6 land, you're better just sucking it up I'm afraid.
As of Java 7, all reflection-related exceptions extend java.lang.ReflectiveOperationException, so you only need to catch that.
The other exceptions (IllegalArgumentException and SecurityException) are unchecked exceptions which you should not be catching at all. If either of those occurs, there's an error in your code. The proper thing to do is not to catch the exception, but to fix the code that is causing the exception.
Specifically, I can see just looking at the code that IllegalArgumentException will never occur, because it only happens if you pass an object to invoke which is not the right type, and I can see that you are passing an instance of the very class whose methods you're invoking. And SecurityException should only happen if you aren't allowed to access the methods at all.

Categories