Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions in Java

I have a question about throwing exceptions in Java, a kind of misunderstanding from my side, as it seems, which I would like to clarify for myself.

I have been reading that the two basic ways of handling exception code are:

1.) throwing an exception in a try-block with "throw new ...", and catching it immediately in a catch-block - the so called try-throw-catch mechanism.

2.) throwing an exception in a method with "throw new ..." and then declaring in the header of the method that this method might throw an exception with "throws ..." - the so called pass-the-buck.

I have recently read that "it doesn't make any sense to throw an exception and then catch it in the same method", which made me think whether I understand the thing in the wrong way, or the person who had written this had something else in mind. Doesn't the first way of handling exceptions does exactly this (the try-throw-catch mechanism) ? I mean, it throws an exception and catches it in the same method. I have read that it is a better practice to throw an exception in one method, and catch it in another method, but this is just one (probably better) way. The other way is also legal and correct, isn't it?

Would you, please, give me a comment on this ? Thank you very much.

like image 328
user42155 Avatar asked Feb 09 '09 14:02

user42155


2 Answers

Exceptions should be thrown from a method when that method is incapable of resolving the exception on its own.

For example, a FileNotFoundException is thrown from new FileInputStream(new File(filename)) because the FileInputStream itself can't handle a case where a file is missing; that exception needs to get thrown so the end-user application can handle the problem.

There are some cases where exceptions could be handled within a method. For example, a Document model method throwing a BadLocationException could be handled within a sufficiently intelligent method. Depending on the problem, either the exception can be handled or re-thrown.

(Anyway, I'd argue that throwing an exception from within a try-catch block so the catch block can be executed represents really bad logic flow)

like image 162
David Koelle Avatar answered Oct 03 '22 08:10

David Koelle


I think you misunderstood the first case. Normally you add a try-catch-block when you call some method which may throw exceptions. Catching locally thrown exceptions indeed doesn't make much sense. In particular you shouldn't use exceptions to exit from loops, as this is extremely slow compared to a standard approach.

like image 24
starblue Avatar answered Oct 03 '22 08:10

starblue