• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Benifit of catching Specific exception when it is printing the same message as Generic exception

 
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Catching the type Exception  is said to be a bad practice and catching the exact exception is good practice. What is the reason for that? Because both are giving me the same messages printed from catch block:

Code while catching specific type




Output:

Exception->java.lang.ArithmeticException: / by zero

Code when catching Exception (bad practice):



Output:

Exception->java.lang.ArithmeticException: / by zero

When in both the cases the output is the same from the catch block then why should one avoid catching Exception type?
Thanks



 
Bartender
Posts: 242
27
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I believe the assumption is that you'd print some more specific error message for what went wrong if you catch a specific exception, for example for NumberFormatException you would say "That's not a number" or something similar. I usually do catch Exception in the bottom-level of the block and print some generic message for them, but catch specific exceptions and give more specific messages for them if I know they could be thrown.

In real life code, I find that people usually just catch Exception.
 
Bartender
Posts: 2911
150
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:Catching the type Exception  is said to be a bad practice and catching the exact exception is good practice.


Please do quote your sources. This would help anyone reading this thread and shows that you have taken efforts to ask a question.

Monica Shiralkar wrote:Because both are giving me the same messages printed from catch block:


Aren't they giving the same message because your code statement is the same in both cases ?
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks all.Understood the disadvantage of using Exception type. If we use specific message we can put our specific message there for understanding it better when we log.  I was thinking it will come from exception type itself but it has to come from our logging statement.

Is it fine to have a catch block catching the generic Exception e at the bottom once we have put the catch blocks of the specific ones?
 
Marshal
Posts: 28425
102
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No. Why would you do that?

You put those catch-clauses in there because you expected that those specific exceptions could be thrown and that you could handle them in a reasonable way. But now you're saying "Well, I don't know what else might be thrown so I'm going to catch those exceptions anyway." But you don't know what's a reasonable way to handle an exception which you don't know what it is. So don't write any code to handle it. These are unchecked exceptions we're talking about here... right?... and so you shouldn't catch them unless you know what to do with them. Just let them crash your program.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:?... and so you shouldn't catch them unless you know what to do with them. Just let them crash your program.



But I want them to write the reason for crashing in a log file before crashing.
 
Paul Clapham
Marshal
Posts: 28425
102
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But look at the code you already wrote. It catches the exception, writes a useless summary of it to the console, and then continues on as if nothing had gone wrong. Now you're saying "An exception happened which I didn't expect, but I'm just going to log it and continue on as if it hadn't happened."

You can't see why that matters because you've written a trivial toy program to illustrate your question, and with that program it really doesn't matter what you do. But with a real program, if an unexpected unchecked exception happens then you don't want to just log it and ignore it. At least, usually you don't want to do that. That's because the code which threw the exception was supposed to do something useful, but it didn't do that. So you need somebody to find out why and fix it as soon as possible, and that isn't going to happen if you just write the exception to a log file somewhere.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But if we dont log then we will not come to know what exactly was the reason for crash.
 
Paul Clapham
Marshal
Posts: 28425
102
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Normally the container you're running your code in will show you the stack trace after the unchecked exception bubbles up to the top. You must have seen that -- don't tell me you never wrote a program which threw a NullPointerException.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:Normally the container you're running your code in will show you the stack trace after the unchecked exception bubbles up to the top. You must have seen that -- don't tell me you never wrote a program which threw a NullPointerException.



Thanks. Yes it shows, but I thought I may add some text in my logging statement like "An error has occurred. The full stack trace is ->" unlike the case of default handler catching it.
 
Marshal
Posts: 80874
506
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I suggest you shouldn't add such a message to a logging file. It will be easier automatically to handle the log file if it doesn't contain such messages.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. But in 90 percent of the catch blocks that  I have come across all the catch block is to log the exception into a log file. Do you mean all that is wrong way?
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:I suggest you shouldn't add such a message to a logging file. It will be easier automatically to handle the log file if it doesn't contain such messages.



But if I dont catch it will not go in the log file at all. If I catch using log.error it will go into the log file.
 
Paul Clapham
Marshal
Posts: 28425
102
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:I thought I may add some text in my logging statement like "An error has occurred. The full stack trace is ->" unlike the case of default handler catching it.



Well, right now all of the code you have written here just logs the description of the exception and not the stack trace. And after it catches the exception, it just lets the code continue as if no exception had happened. So your code fails to display what you want to do, and it fails to do what you ought to do.

If you're running a Java program from the console and an uncaught exception is thrown, then the stack trace is written to the console. Your code wouldn't do that. If you're running a web application and one of your web components throws an uncaught exception, then the server will catch the exception and write it to the server log. In neither of those cases do you need to write special code to deal with uncaught exceptions, which is the reason why the Java designers invented unchecked exceptions. So that's two examples of the "default handler" which you claim doesn't write the stack trace anywhere.
 
Campbell Ritchie
Marshal
Posts: 80874
506
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:. . . But if I dont catch it will not go in the log file at all. . . .

We appear to have completely misunderstood each other.
 
salvin francis
Bartender
Posts: 2911
150
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:... Thanks. Yes it shows, but I thought I may add some text in my logging statement like "An error has occurred. The full stack trace is ->" unlike the case of default handler catching it.

I think what Paul is referring to is what you do after logging the exception. Are you aware of the mechanics of bubbling up an Exception ?
 
Sheriff
Posts: 17734
302
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:Thanks all.Understood the disadvantage of using Exception type. If we use specific message we can put our specific message there for understanding it better when we log.  I was thinking it will come from exception type itself but it has to come from our logging statement.


This is missing the main reason for declaring catch blocks with specific exception types. The point is to not cast such a wide net but only catch the exception you're prepared to handle.

If you're fishing for salmon and you cast a net that will catch everything in the water, then you'll be catching way more creatures than salmon, right? Why do that? If you're fishing for salmon, then you only want to catch salmon. You don't want to catch crabs, or dolphin, or whales, or old tires. By catching Exception, that's basically saying "I will handle every manner of exception." That's fine if it's the last option in a chain of catch blocks where you filter out specific exceptions.

As far as development practice, you should be testing enough so that unchecked exceptions that indicate logic/programming errors are allowed to crash your program. Then you can address the problem before you go to production. If an unchecked exception that's caused by programmer error happens in production, then what you need to look into fixing is not only the bug but the problem in your development practice that allows such things to happen. The fact that you're only logging things in catch blocks indicates to me that your exception handling strategy may need a little bit of scrutiny and maturity.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote: If you're running a web application and one of your web components throws an uncaught exception, then the server will catch the exception and write it to the server log. In neither of those cases do you need to write special code to deal with uncaught exceptions, which is the reason why the Java designers invented unchecked exceptions. So that's two examples of the "default handler" which you claim doesn't write the stack trace anywhere.



Thanks. Understood that it would still write to the logs. E.g Catalina log of tomcat.

If I am using say log4j and logging to my own log file, would that still be logging there in this case?
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

salvin francis wrote:

Monica Shiralkar wrote:Are you aware of the mechanics of bubbling up an Exception ?



Yes. For the checked exceptions, from the inside layers, we dont catch the exception and instead use throws. Only in the outermost layer, we catch the exception.

 
Junilu Lacar
Sheriff
Posts: 17734
302
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:Yes. For the checked exceptions, from the inside layers, we dont catch the exception and instead use throws. Only in the outermost layer, we catch the exception.


What is your source for this statement? That's a very definitive statement and it's not correct. It depends entirely on the context where you handle the exception. Whether it's in an "inner" layer of your application or "outermost" layer has nothing to do with it.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:that's basically saying "I will handle every manner of exception." That's fine if it's the last option in a chain of catch blocks where you filter out specific exceptions.




But as discussed above in the post, even for the last option in the chain of blocks, it would in any case be caught by the default handler and shown on the console or catalina logs (in case of web app deployed on tomcat)?
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:
If an unchecked exception that's caused by programmer error happens in production, then what you need to look into fixing is not only the bug but the problem in your development practice that allows such things to happen.



Thanks.I know that we should not be catching NullPointerException and instead be putting checks in code. Does this hold for each and every runtime exception?
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:It depends entirely on the context where you handle the exception. Whether it's in an "inner" layer of your application or "outermost" layer has nothing to do with it.



If I have a REST API in which delegates the work and eventually the repository layer fetches the data from DB and returns, then throw the exception everywhere except for the controller layer and catch it only when it reaches here.
 
Campbell Ritchie
Marshal
Posts: 80874
506
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:. . . we should not be catching NullPointerException and instead be putting checks in code.

I don't think that is correct. It is often better to keep nulls out of your code, which may involve throwing more NPEs in the development stage.

Does this hold for each and every runtime exception?

No.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote: often better to keep nulls out of your code, which may involve throwing more NPEs in the development stage.



The way I know is instead of catching NullPointer exception, put a null check condition in the code using ==. What does keeping nulls out code mean?
 
Junilu Lacar
Sheriff
Posts: 17734
302
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:put a null check condition in the code using ==. What does keeping nulls out code mean?


It means preferring designs that make it unnecessary to check for == null all the time. For example, if a method returns a List, never return null because that causes clients of your method to check for null. Instead, return an empty List. Another way is to employ the Null Object Pattern. While there are certain cases where it might be appropriate to return null, it is often the case that return null was just a lazy or rushed decision on the part of the programmer. Spend more time contemplating your design and ask yourself if there's a better alternative to returning null. This requires a lot of practice.
 
Monica Shiralkar
Ranch Hand
Posts: 2969
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. More than 90 percent of the catch blocks I have seen in codes have a logger doing log.error statement for the message. Some of them have System.exit(0) as well after the logger. May be for log.error , since it will be automatically done (for e.g to Catalina file in case of web application on tomcat) so it may not make sense to log it. So means, first the code is preventing the program to exit on getting the exception, then catching the log (which is not required) and then doing system.exit(0) to make it exit. That would not make sense.
 
Campbell Ritchie
Marshal
Posts: 80874
506
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:. . . catching the log (which is not required) and then doing system.exit(0) to make it exit. That would not make sense.

Agree there. Closing the app with System.exit(...); might do even more harm. I shall let you work out a few examples. Also why you shouldn't use 0 as the argument.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic