r/javahelp • u/alfavaca_x • Jun 30 '21
Why do we need to catch specific exceptions instead of just catching any Exception?
Why do we need to do:
catch(FileNotFoundException ioe){};And not:
catch(Exception e){};My professor says it "does not promote robust implementation", but he doesn't explain what that means.
39
u/eggboy55 Jun 30 '21
The whole point of try-catch is to try something, and then IF that thing fails, try to recover. This is commonly caused by a 'contract' of some form being broken - e.x the user is asked to input a number, but instead inputs a string. Or the program asks for a file that doesn't exist.
Without specifying the exact error, how can you know how to recover? If it's a 'FileNotFoundException', then we can get a pretty good idea of how to deal with it (e.x create the file if it doesnt exist // ask the user to select a different file path).
If we just catch 'Exception E' what exactly do we do with that? We can't recover from a problem without knowing the root cause. If an error is caused by a nullpointerexception, i do NOT want to handle it with the same recovery that I use for a FileNotFoundException.
14
u/alfavaca_x Jun 30 '21
That's simpler than what I was expecting. Thanks, I understand.
5
u/FrenchFigaro Software Engineer Jul 01 '21
More about that, on the robust implementation part that your professor mentioned:
All exceptions classes inherit
Exception. All of them, no exception (pun intended). But not all exception need to be caught outright. /u/eggboy55 mentioned theNullPointerException. In the application I am working on, and based on the API contract my application consumes, such an exception would indicate either a grave discrepancy in data integrity, or a grave programing error on my part.So grave in fact that it can't be recovered trivially, so I don't want it to be caught. I want it to be propagated to the uppermost level of my application and result in my rest controller popping out the dreaded Internal Server Error.
The
catch(Exception e)clause is a incredibly tight net that catches everything but the gravest problems (indicated by the classesErrororThrowable, which you should not catch either, generally speaking). There are cases where such a catch-all is warranted, but they are exceptions to the rule and as a teacher of mine once said: "Everytime you are tempted to do it, you must think long and hard about why you want to do it, and then not do it anyway."
15
Jun 30 '21
You can catch all exceptions, but it's often useful to have your program do different things to gracefully recover when certain exceptions are thrown, or to log more interesting messages with relevant information for debugging.
4
u/__helix__ Jun 30 '21
It helps describe what the issue is. The warning is typically "Avoid Throwing Raw Exception Types". At our shop you are required to handle and have a test for every subtype of exception thrown. If you say Exception, the great grand daddy of all classes - some joker will be obligated to ask where your SQLException test is, since your file operation obviously needed it. (if a third party framework hands you that potato, you are exempted).
If you spell out the specific exceptions, you can make the troubleshooting much easier.
try(Thing something = autoclosableThing()){
thingsGoBoom();
} catch(ThisException | ThatException e){
doThisOrThat();
} catch(TheOtherThing e){
somethingElse();
}2
u/rickybwr Jul 01 '21
It helps to be more specific while catching the errors, using alternate flows and logging them. Though, we can use Exception to catch all the exceptions, but it won't help us in case we want to perform certain tasks specific to the error.
2
u/steave435 Jul 01 '21
Beyond the functional aspects other people have described, I want to make this more general - whenever you can make something clearer, you should do so.
Software needs to be maintained, and it will likely be worked on by multiple people. You should do everything un your power to ensure that reading and understanding your code is as easy as possible to make that job easier for the maintainer/other dev, whether that's someone else or just you a few months or years later when you no longer remember what you were thinking when you wrote it.
Writing out the type of exception you expect might happen helps the reader with understanding what might go wrong at a glance without having to read trough the entire try, and if you have a good IDE, it might even help you realize that you forgot to cover a potential exception that you didn't think about.
It may not matter at your current stage, but it will eventually, and the sooner you start practicing writing clean code, the better you'll be at it when it does matter.
1
u/darkecojaj Jul 01 '21
You use it to deal with issues. Imagine you were grabbing data from a database and putting it in a pojo (basic Java class object)
In the case of the database, you could result in many errors, the two big ones being a connection issue and a query execution issue due to an error in the query. In the connection issue, you might want to catch it and retry the connection or give the user a warning the db cannot be connected to while with a query error (such as trying to create a new row with an existing Primary key), you'd want to inform the user it's not valid and to try another one. You may also run into issues with converting values, nulls, an any other assortment. Having a plan to handle these are good and one generic plan cannot cover all of them.
On top of that, even if you expect to only have 1 possible exception, it is good to catch by its name in case a rare case scenario comes and a different exception happens. This way you realize its different and prepare you system for it in case it happens again.
1
Jul 01 '21
In any method, there are exceptions you can handle and exception you can't handle. Don't catch the ones you can't handle: just let them bubble up and eventually they will be caught by a method than can handle them. Only catch the ones you can do something about.
-5
•
u/AutoModerator Jun 30 '21
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.