0

I have a lot of lines inside one try catch blocks . I want to make it such that even if any lines throw any error inside try block , try block should continue to run from next line onward. I hardcoded it with switch and case and whenever an error occur inside a case , my catch block knows which case has the error occurred and I can just recall the method containing try catch block from next case onwards. But i do not want to hardcode it this way and also do not want to use multiple try catch blocks. But the problem with using one try catch block is if something causes an error inside one line of try block then all lines written below it do not run at all , despite them having no relation with the error causing line . Is there a better way or alternative out there to solve my problem ?

  • 1
    try..catch is meant to throw exception and not able code to continue its execution. You have no choice to use multiple try..catch – Teo Aug 06 '21 at 02:00
  • Your question is unclear. Please show us some code to illustrate what you are asking. – Stephen C Aug 06 '21 at 02:00
  • 2
    That's kind of the opposite of what exceptions are made for. If your app can logically continue after an exception is thrown, it probably shouldn't be an exception. Recovering after an exception is a rare corner case. – Gabe Sechan Aug 06 '21 at 02:03
  • @Teo - There are some alternatives; e.g. write a method whose purpose is to perform an action (supplied as a lambda or method reference parameter) and catch the exceptions. But you need to be cautious in apply such techniques ... 'cos it can make the code harder to understand. – Stephen C Aug 06 '21 at 02:05
  • yea I aware of that, but the general idea is to throw exception – Teo Aug 06 '21 at 02:11
  • *despite them having no relation with the error causing line* If they have no relation with the error causing line, then these lines belong in different methods. If there is a relationship such that the program can't continue (such as can't open a file, the rest of the code that ***reads*** the file is going to fail) then it makes sense to group such code. Otherwise, split it up. – Elliott Frisch Aug 06 '21 at 02:14
  • If you *have to* throw exceptions and want to handle them gracefully, that's try-catch. If it were really a lot of blocks I would consider putting it in a function(s) which takes a function as a parameter and runs it inside the try-catch https://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java – clwhisk Aug 06 '21 at 02:29

0 Answers0