try {
if (isFileDownloaded)
// do stuff
else
throw new CustomException()
}
catch (Exception e)
{
// something went wrong to save the error to log
}
finally
{
//release resources
}
My question is would the catch
catches the ApplicationException
thrown in the try block? is it in poor coding style?
Should it be written in another way?
The catch
will catch your exception (and any other that occurs). That being said, I try to avoid writing code like this when possible.
Personally, I see little reason to ever have exception handling (catch) for an exception thrown in the same scope. If you can handle your error in your method - put the exception handling (ie: logging) directly in the try block as well.
Using a catch
is more useful, IMO, for catching exceptions thrown by methods within your try
block. This would be more useful, for example, if your // do stuff
section happened to call a method that raised an exception.
Also, I recommend not catching every exception (Exception e
), but rather the specific types of exceptions you can handle correctly. The one exception to this would be if you're rethrowing the exception within your catch - ie: using it for logging purposes but still letting it bubble up the call stack.