Reputation: 895
When I try using a try/catch I am confused as to what type of errors to try and catch. In doing research here in stackoverflow I have seen the comments on not recommending the use of
catch(Exception e)
as it is to generic but where can I find what type of specific errors I should look for an example would be trying to play an audio file using pseudo code
try{
play audio file
}
catch ( invalid file)
catch ( bad connection)
catch ( file not found)
catch ( invalid file size)
etc
The pseudo errors I list above cover a broad range of functionality from internet connectivity to file specific information.
How do I cover all of these cases
I have an App that shows a message that says the file cannot be played but I would like to catch the specific error and see what is happening each time this message could appear and fix it.
What if I wanted to try and catch an error for something that is unique that I code myself.
This may be a bad example but if I want to calculate the duration of a planets orbit and generate an error if the duration is smaller than some value. The values used should cause an area to be over 13 months but for some UNKNOWN reason something causes it to be below 13 and I want to find out why so I use a try catch because something is wrong and I do not know what it is, maybe I need to use a absolute value of a number instead of the number itself or something similar the main point was I do not know what the error was caused by.
Upvotes: 3
Views: 224
Reputation: 476
The only way you will know what to "Catch" is by looking at the method definitions as they will state what exceptions will be thrown. If you want a generic catch all then you already have it with Try Catch as the Exception Class is the base Class for all other Standard Exceptions
Upvotes: 0
Reputation: 23265
You can catch specific errors by specifying a particular type to catch:
try {
...file open...
} catch (IOException e) {
...handle IO exception...
}
There's a giant list of exceptions, all subclasses of Exception
. The exceptions are organized in a hierarchy, so some subsume others. For instance, EOFException
is a subclass of IOException
, so if you want to catch any IO error (including EOF errors) use IOException
, if you only want to catch EOF in particular, use EOFException
.
You can write your own sublcass of Exception
(or one of its subclasses), and catch it like any other predefined exception.
Upvotes: 3