Throwing exceptions in Java

I have a question about how to throw exceptions in Java, something like a misunderstanding on my part, it seems to me that I would like to clarify for myself.

I read that there are two main ways to handle exception code:

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

2.) throwing an exception into the method with "throw new ...", and then declaring in the method header that this method can throw an exception using "throws ..." - the so-called pass-the -buck.

I recently read that โ€œit makes no sense to throw an exception and then catch it with the same methodโ€, which made me think if I understood something wrong, or the person who wrote it meant something else . Is this the first way to handle exceptions (try-throw-catch mechanism)? I mean, it throws an exception and catches it in the same method. I read that it is best to use an exception in one method and catch it in another way, but this is just one (possibly best) way. Another way is also legal and correct, right?

Could you give me a comment on this? Thank you very much.

+4
source share
11 answers

Exceptions should be excluded from the method when this method cannot solve the problem on its own.

For example, a FileNotFoundException thrown from new FileInputStream(new File( filename )) , because FileInputStream itself cannot handle the case when the file is missing; this exception should be thrown, so the end-user application can handle this problem.

There are cases where exceptions can be handled inside a method. For example, a document model method that throws a BadLocationException can be handled as part of a fairly intelligent method. Depending on the problem, the exception may be handled or re-selected.

(Anyway, I would say that the exception from the try-catch block excludes the catch lock, is a really bad logical stream)

+20
source

I think you misunderstood the first case. Usually you add a try-catch block when you call some method that can throw exceptions. Capturing locally thrown exceptions really doesn't make much sense. In particular, you should not use exceptions to exit the loops, as this is very slow compared to the standard approach.

+6
source

Not the first way to handle exceptions is doing just that (try-throw-catch mechanism)? I seriously throw an exception and catch it in the same method.

This is not a "way to handle exceptions" - it is complete nonsense. The whole point of exceptions is to allow another method to control the call stack. If you are going to handle the condition within the same method, it makes no sense to use an exception - this is what for if ()! If this complicates the control flow of your method too much, you should probably reorganize some of the logic into separate methods - and then it may make sense to throw such an exception that catch the remaining method object.

Having said that, I can present one particular case when it would be reasonable to throw and catch an exception in the same method: when you already call a method that can throw an exception and have a catch block to handle it, in some cases it would be reasonable to throw an exception to indicate a similar problem that an existing catch block can handle in the same way.

+4
source

The person who wrote โ€œit makes no sense to throw an exception and then catch it in the same methodโ€ has the right to his opinion, but it is not widespread. There are many cases when throwing and catching an exception in the same method is what you need. The simplest is where you perform the sequence of operations, and the failure of any of them makes the rest invalid. If you find that one of these operations fails, it is quite reasonable to throw an exception and catch it at the end of the method. This is actually a logical way of doing things. You might be able to rewrite the code to not use an exception, maybe with some status flags and a break statement or two, but why do you need it? Using an exception allows you to understand what is happening and improves the readability of the code.

+3
source

I am going to answer your questions in turn, and then add some comments to the end. I am not an authority on exception handling, but I hope my comments are helpful.


"Not the first way to handle exceptions is doing just that ??

My answer is yes, as you describe it, the first method works by throwing and catching an exception in the same method. However, I don't know that try-throw-catch should work when you describe it.


โ€œI read that itโ€™s best to use an exception in one method and catch it in another way, but this is just one (possibly the best) way. Another way is also legal and correct, is that?โ€

I agree that it is better to learn the exceptions from the second method, but the first method is finished. Is it correct? well, what is up to you to decide is your code, after all.

For the most part, I agree that it makes no sense to throw an exception, and then immediately catch that exception in the same method. If we do this because the method is especially long / complicated, and handling the error using a different logic will complicate the situation, then I would suggest moving part of this logic to another method and calling this method and catching its exception.

If our code is simpler, then it can be easy to deal with the error using code that does not consist of throwing exceptions.


My comments:

The try-throw-catch mechanism you mentioned may not need to be thrown by the same method. I would need to read a text that you thought was specific, but I would expect this to not be necessary. If an exception is not required for this exception, then your exception handling strategy is a combination of 1) and 2).

In combo, one method will use the try-throw-catch mechanism to catch the exception caused by the called method. It seems to me that 1) and 2) should work together to form your exception handling strategy.

Now, maybe someone will come and give us some wonderful reasons why we might need to eliminate an exception in the same method. I expect there are some, but to me they seem to be exceptions, not the rule.

Cheers ed

+3
source

In the first case, you mean something like this:

 try { ok = doSomething(); if (!ok) { throw new Exception("Error"); } ok = doSomethingElse(); }catch (Exception e) { } 

This will allow you to exit the try-catch block without doing the rest. This is the only valid use I can think of throwing an exception with a throw and catching it myself in a try-catch block. However, building blocks should be used instead. I do not understand why someone should throw an exception and then catch it myself.

The second method is more standard, especially if the calling method that throws the exception is an external module. This is a way to signal that something real has happened. The responder must handle the exception.

+2
source

If you are going to manually throw an exception, then obviously you know that some error needs to be handled. Instead of throwing a new exception, then catching it and then immediately handling the error, why not just handling the error? You (and the processor) do not need to go through all the work of throwing an exception and catch it. The exception also makes reading and debugging code difficult.

You have selected an exception instead of immediately reporting an error if:

  • Other code, such as code called your method, should handle this error. For example, if your code is not user interface code, then it probably should not create windows. This is your number 2 method.

  • You can use the try, catch, finally function. You could probably write cleaner code this way, but I think that in 90% of cases your code will be more readable using simple if statements.

+2
source

My expropriation is that using the first method your code cannot be read quickly - because the functionality and error handling are mixed. BUT , this makes sense in some cases when you have an attempt {} catch {} finaly {} - for example, when processing files or processing a database where you ALLWAYS want the connection to be closed.

 try{ //do something }catch(Exception ex){ //log }finally{ //connection.close } 

For everything else, I use the second option - just to centralize my error handling procedures and maintain readability of the code that implements the business logic itself.

+1
source

In my opinion, try the blocks you write should not include any โ€œnew throwsโ€ that are caught inside the same method. When you throw an exception, you say: "I am faced with a situation that I can not handle, someone else will have to deal with it." Your method with "throw new" must either throw an exception, or throw or declare a checked exception in its method signature.

If you use third-party classes that can throw exceptions, your method should have a try / catch block if you can really handle the situation if an exception occurs. Otherwise, you should defer to another class that might.

I do not create my own exception and then catch it in the same method.

+1
source

The use of exceptions for control flow is specifically addressed in Effective Java, 2nd Edition by Joshua Bloch, paragraph 57:

Paragraph 57: Use exceptions for exceptional conditions only

... exceptions, as their name implies, are used only for exceptional conditions; they should never be used for normal control flow. [italics mine]

Therefore, although it "works" to use exceptions to control flow, it is not recommended.

+1
source

The reason why this might seem pointless (throwing and catching in the same method) is because it would be a script to use exceptions to control the flow. If you already have enough data to determine the condition in which the exception should be thrown, you can use this information to use the condition.

See below:

1) Throw and trap exceptions in the same method ( incorrect )

 public void method() { try { workA... workA... workA... workA... if( conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) { throw new IllegalStateException("No the rigth time" ); } workB... workB... workB... workB... } catch( IllegalStateException iee ) { System.out.println( "Skiped workB..."); } workC.... workC.... workC.... workC.... } 

In this scenario, throwing exceptions is used to skip the "workB" section.

This is best done as follows:

2) Use of conditions for flow control ( right )

 public void method() { workA... workA... workA... workA... if( !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) ) { //throw new IllegalStateException("No the rigth time" ); workB... workB... workB... workB... } workC.... workC.... workC.... workC.... } 

And then you can reorganize the condition:

  if( !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) ) { 

for

  if( canProceedWithWorkB() ) { 

implemented as:

  boolean canProceedWithWorkB() { return !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() ); } 
0
source

All Articles