• Post Reply Bookmark Topic Watch Topic
  • New Topic

should I add throws clause to main method or catch that exception in main method?  RSS feed

 
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Should I add throws clause to the main method and throw Exception or should I catch the Exception type inside main method?
thanks
 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That depends on whether you want to handle the exception in the program or to let it cause the program to fail and report the exception.
 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks. what will be the difference in both cases? I mean the program will stop in both cases.
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Monica Shiralkar wrote:thanks. what will be the difference in both cases? I mean the program will stop in both cases.


In the first case, you are handling the exception. Whether the program terminates, or not, is completely up to you (and how you are handling it). In the second case, where the exception is thrown by the main() method, then that exception is handled by the default exception handler, which by default, prints out the exception (along the a stacktrace) and terminates.

Henry
 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have my own opinion about this. It is very simple.
Monica Shiralkar wrote:Should I add throws clause to the main method and throw Exception or should I catch the Exception type inside main method?
thanks
No.

Shall I explain a bit more?

The main method is for starting the application off. I gave you a link about that earlier today. As Bear said, it is a case of: what you are going to do to handle the exception? Note that I am using the w‍ord exception in the same sense as this Java® Language Specification section does throughout. Let us imagine you have a call stack like this:-Let us imagine that the method in line 10 declares that it might throw an ABCException if the dwoil is flunked backhand.

Now, what are you going to do about it? There are lots of things you can do with an exception, and I am sure you know them, so I don't have to strain my brain trying to enumerate them. You have to decide that, then you have to decide where to do it. You probably can't do it in one of the Socket methods because they are outwith your control, but maybe you can handle it in lines 5‑7. I think there is another place where you shouldn't handle an exception: the same place as it is thrown. If you can't handle the exception, where can you handle it? You might be able to give more details and click the button again, so maybe in the actionPerformed method too.
But I am pretty sure that you can't handle an exception in the main method. If you want your app to run, then you will have to handle all checked exceptions somewhere else, so they never reach the main method. If an unchecked exception reaches the main method, it is probably impossible to sort it out there, so you might as well allow it to propagate and the current Th‍read to terminate. Of course you don't declare unchecked exceptions with a throws clause anyway. Remember that an unchecked exception is one which the program cannot reasonably recover from. [At least that is the theory, as explaines in the Java™ Tutorials.]

∴ You neither declare an exception as thrown from the main method, nor catch it there. If you have a checked exception which reaches the main method, you haven't worked out correctly how to handle it elsewhere.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Monica Shiralkar wrote:. . . the program will stop in both cases.
The whole idea of catching an exception is so as to keep the program running. You probably shouldn't catch an exception and stop the program.
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I disagree Campbell. It depends on the intended user of the application. If a checked exception is able to reach the main method, and there's no good way to recover from it, then the application can just crash with a stack trace if the intended user is another developer. If the intended user is a less technical person, it's better to output a more friendly message.

It all depends on the requirements of the application.
 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks All. I want to improve the exceptional handling of my core java application to follow good programming practice. As of now, whenever the Eclipse gave compiler error message "You must catch exception or add in throws", I have conveniently added in the throws. Also wherever I have caught some exception. All I have done is logged the exception.  What changes should I do to follow a good programming practice regarding exception handling.
 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good programming practice? Well, as Bear said back at the beginning of the thread:

That depends on whether you want to handle the exception in the program or to let it cause the program to fail and report the exception.


In other words, good practice starts with you deciding whether your code can and should handle the exception. Don't expect good practice to make this decision for you, either; it's entirely dependent on your application and what it's supposed to do. There have been several posts in this thread with good points about whether you should let an exception propagate to a higher level (and note that these points mostly apply to all methods, not just the top-level main method).

So there aren't any rules which are independent of the context and which tell you what choice to make. The answer (as it often is) is "It depends". If you don't find the discussion here to be helpful, perhaps you should post an actual example where this question arose and describe it here for people to discuss.
 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bear Bibeault
That depends on whether you want to handle the exception in the program or to let it cause the program to fail and report the exception.


All I want to do (can think off) is to log the exception.

thanks
 
Paul Clapham
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's probably a good solution in a lot of cases. But I often find that discussing abstract concepts doesn't necessarily help me decide what to do in specific cases. When I see a few realistic examples I find that I can extrapolate from those examples to code that I want to write. But different people have different learning styles and there are those who can examine an abstract concept (like checked exceptions) and convert it to practical decisions about their code.

However it seems that you're like me in this case, that's why I suggested discussing specific examples.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:. . . If a checked exception is able to reach the main method, and there's no good way to recover from it, . . .
Why shou‍ld checked exceptions propagate as far as the main method? Once they get that far, it is going to be impossible to handle them properly. You might have no option other than to declare the exception. If a checked exception reaches the main method, it is going to be difficult to produce an error message more helpful than simply, “Something has gone wrong.” If you suffer an IOException in a method for reading, you can produce messages like, “Please check integrity of network, otherwise try again later.”

It will be different with unchecked exceptions; you can simply let them propagate. There is no way the end user can work out why you have got an NPE, but the developer ought to have tested and found out where the stray null is so you never suffer the NPE at all.
But maybe my opinion is a bit extreme after all. Maybe I am in a dream world.

As for logging, what is wrong with logging exceptions? You need to be circumspect about logging, however. When you open your log file which you haven't looked at for 12 months and find it contains 38475129375384 messages, 99.9% of them about trivia, you have got problems. Logging exceptions puts a responsibility on you to read the log file frequently. It is probably a good idea to restrict logging to serious things, too. And anything in the log file requires you to consider whether there is an error in the code. Lots of out of memory errors about heap space shou‍ld make you do profiling about memory consumption and maybe add instructions for users about it. Lots of illegal argument exceptions about, “Negative numbers not acceptable here,” need looking at. Maybe you can prevent them with loops:-It would be a little more difficult on a Swing app, but not much more difficult. The Unicode escape is a posh apostrophe. In a lot of cases with exceptions, “Prevention is better than cure.”

You have all sorts of options about exceptions; you often ought not to handle unchecked exceptions at all. You must do something about checked exceptions however. As everybody has said, you need to decide what sort of exceptions might be thrown, what you are going to do if such an exception occurs, and where you are going to do it. These options include
  • 1: Your method says, “I might suffer an XYZException, but I don't think I can handle it correctly myself.” The Java® spelling is throws XYZException. Deciding that a particular method cannot handle that exception is part of the process. I think you shou‍ld never throw any exception and catch it in the same method. That is simply equivalent to an inefficient for of if‑else.
  • 2: Squelch the exception. The Java® spelling is ...catch (XYZException exc) {}. As anybody will tell you, an empty catch is a dangerous thing.
  • 3: Log it.
  • 4: Rethrow it.
  • 5: Throw a different exception object (possibly with the current exception as the cause; this is called exception chaining).
  • 6: Error message. The stack trace counts as a sort of error message.
  • 7: Error message in loop. This gives the end user the option of trying again.
  • 8: etc., etc.
  • In each case, you will have to decide which of those to do, or whether to do several of those options. If you decide that your current method isn't the right place to handle the exception, you will probably use option 1.
    As people told you, consider how you are going to handle any exceptions, and also what it will look like for users. A developer will find a stack trace much more helpful than simply, “Something has gone wrong,” but stack traces are totally incomprehensible to 99.99% of end users.
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    By the way, how many checked exceptions do you suffer? I have the impression that I put effort into catching checked exceptions and nothing ever happens about them. I put just as much non‑effort into not handling unchecked exceptions and they seem to happen frequently.
     
    Monica Shiralkar
    Ranch Hand
    Posts: 922
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks..
    I could not understand what does the below mean and if not so then what is the way?

    "Why shou‍ld checked exceptions propagate as far as the main method? Once they get that far, it is going to be impossible to handle them and properly."
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Start by reminding yourself of the ideal length for a main method: one statement.
    Now you write an ideal length main method:-Now add some exception handling:-Now, tell me, how you are going to handle that Exception? Believe it or not, you can produce a very simple comprehensible and truthful answer to my query
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7993
    143
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:Why shou‍ld checked exceptions propagate as far as the main method? Once they get that far, it is going to be impossible to handle them properly. You might have no option other than to declare the exception. If a checked exception reaches the main method, it is going to be difficult to produce an error message more helpful than simply, “Something has gone wrong.” If you suffer an IOException in a method for reading, you can produce messages like, “Please check integrity of network, otherwise try again later.”

    I don't see any reason to avoid calling methods that can throw checked exceptions from the main method, so checked exceptions can easily reach the main method. An example: let's say that the main method first calls a method that is responsible for reading configuration settings from a file, and then it initializes some controllers or other classes using that configuration. If there are problems reading the file, an IOException can propagate to the main method. Now, if the application is meant to be used by some end-user I agree that effort should be made to print out a descriptive message, instead of letting the application crash with a stack trace. However, if I'm just throwing together a command line tool that is going to be used in-house to make some development task easier, I'm not going to waste my boss' time by carefully crafting error messages, when my fellow developers can just as easily read a stack trace, which is going to be more informative to them anyway.
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I think we are going to have to agree to differ.
    Actually, I think the difference is actually lessening with more explanation. If you are using that sort of approach during development and testing, then it would be quite all right to handle checked exceptions in the main method. I take your point about the stack trace; for something used by developers you have the choice between letting the exception propagate and writingAgree that is a good way to handle such errors by developers.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!