In Java we can catch exceptions of a certain type:
try{
// Code that does IO like download a file...
}catch(IOException ioe){
ioe.printStackTrace();
// handle ioe
}catch(SomeOtherException soe){
// handle soe
}
Now, there can by many causes to an Exception, in this case, the IOException
can be:
java.io.IOException: Illegal character in path at index.....
from a specific library or some other like:
java.io.IOException: Stream closed ...
If something went wrong with a Stream
Now, my question is, how do I determine what kind of IOException
happened?
How do I distinguish between a Stream closed
and Illegal character in path at index...
?
Of course I can just check the String of the exception message but I don't think it's the best way since the underlying library/implementation can change the message string.
EDIT:
e.getClass()
in this case returns java.io.IOException
for almost everything...
I guess the library throws their own IOException
while discarding any original Exception
.
The term exception is shorthand for the phrase "exceptional event." Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program.
Difference Between Checked and Unchecked Exceptions in JavaA checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.
Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error.
The fact that the printStackTrace
printed
java.io.IOException: Stream closed ...
// ^^^^^^^^^^^
and
java.io.IOException: Illegal character in path at index.....
// ^^^^^^^^^^^
means the Exception
is of type IOException
. There isn't a more specific subtype you can use here.
There is no way in this case. They decided to use the same Exception
type for both (and more) of those reasons. You won't be able to distinguish them with different catch
statements. You'll need to check their message.
If the Exception
has a cause
, you'll have to see if there's a distinguishing type and rethrow it. If you're lucky, you might be able to catch a more specific type of Exception
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With