I notice this is a lot of places I work they use a try catch and when they catch the exception all they do is throw the exception again, Why is this? For example it maybe try to post this and if it fails catch the exception and then log a message and throw the exception again are we just catching it to throw a log message or is there a purpose to it?
#Java Exception
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
e data to a database and if there is an exception, they catch it and throw it again. Is there any benefit to doing this?
Yeah the purpose is just to be able to do stuff with the exception like logging etc
but then why is it thrown again?
Because the method doesn’t run properly
That’s why you have an exception
And imagine method1 depends on method2 to successfully run, maybe it needs the return type
But method2 got an exception internally, catches it and logs it, then method2 can’t successfully finish and not return the expected instance and thus throws the exception again
And then method1 gets an exception because it can’t get the expected instance it might work on from method2
Sometimes those methods don’t catch and log on their own
But rather have an universal handler that does stuff like logging upon exception in that application
and usually its not up to the method itself todo a fix for the problem, but one higher up the chain, the logging is there to find out where the problem occured
like in Squid's example, method 2 calls method one for an instance of something, get nothings but recieves a thrown exception. Goes in the catch block and generates a new instance
so the error propogrates up higher
e.g. if it's a rest API, you might have a top-level handler that may return a 500 error on exceptions
but you still want logging and error handling for those specific functionalities