Java Exception Handling - is this good practice? - java

I am working on a Java plugin for a framework.
I have written my code in such a way that entryPoint function looks like below (consider this is the starting point, main function)
function entryPoint()
{
try{
//some code block
subFunction1();
subFunction2();
}
catch(Exception e) {}
catch(IOException ioe) {}
catch(NullPointerException npe){}
}
function subFunction1() throws IOException
{
//some code
}
function subFunction2() throws NullPointerException
{
//some code
}
So the idea is, all the sub functions throws specific exceptions to major function and
we catch these exceptions in the major functions and do handling.
Is this way correct? If not please suggest better way.

The order of the catch statements should be changed. Since the first catch will match all Exceptions, the following two will never be triggered.
An NPE is in most cases unexpected and not recoverable. Catching it implies that the application is able to recover from it and run regardless. Is it really the case?
Even if the NPE is recoverable, it is a better practice to check for != null instead of relying on exceptions for command flow. This is for conceptual reasons (exception-based command flow requires more code, is less readable, the intention is often unclear) as well as for performance reasons.
All Exceptions are swallowed - no logging or rethrowing happens. This way, no one will know if and when something goes wrong because there are no exceptions logged. In most cases, users, other developers and maintainers expect almost all exceptions to be truly exceptional and therefore logged.

Do not catch or throw NullPointerException and Exception's catch block should be the last one

I think this approach is perfect. One should try to handle specific exception rather handling all in one. Putting a try-catch block just for the heck of it is not use of it, but abuse of try-catch thing.
Yeah Exception should be the last one to be handled.Missed this.
In short your intent is good and syntactically you can depend on compiler.

You should do the exception-handling the same way you would do it, if it was no plugin. It depends on you application, if you can handle all exceptions in one major method. If there are case, in which you can continue work, than this could be difficult this way.
The only thing that I would do regarding the plugin-thing is an all surrounding 'catch-all' and maybe some special cases to do some more detail logging. And this also has just to be done, if the framework doesn't do it itself.

I think it is best to catch an exception at the first possible place where you can actually resolve the resulting problem.
An example:
function int divide(int a, int b) throws DivisionByZeroException {
if(b == 0){
throw new DivisionByZeroException();
}
return a / b;
}
function int doCalculationsAndStuff(int a, int b) throws DivisionByZeroException {
int result = divide(a, b);
...
return result;
}
function void main() {
try {
int a = userInput();
int b = userInput();
int result = doCalculationsAndStuff(a, b);
print("result: " + result);
} catch(DivisionByZeroException e) {
print("Division by zero happened. But i catched it for you =).");
}
}
It wouldn't make sense to handle the exception in divide() or doCalculationsAndStuff(). Because what value would you return in case of a division by zero? Nothing, right that's why we throw the exception and handle it in the main function where we give the user of our calculator app some feedback.
Now back to your question. If the entryPoint function is the first place where you can resolve the problems that occur in your subfunctions than thats a good place to handle them.

Related

How to return inside a try-catch in a recursive method?

I dont get why I cant return a value inside my code, there it is :
private int depth(Position<Integer> p) {
try{
if (ab.isRoot(p))
return 0;
else
return 1+depth(ab.parent(p));
}catch(InvalidPositionException | BoundaryViolationException e) {System.out.println(e.getMessage());}
}
It's not detecting the return. I know it is inside a try-catch and it could capture an exception, but I'm confused because in the book I'm reading (Data Structures and Algorithms - Goodrich & Tamassia 4th edition) he's not sending an int in the parameters (which could be usefull in the recursion to save the value)
EDIT: Solved, thanks you all!
It is "detecting" the return.
It's just that you don't have an explicit return on all program control paths: you need to return something in the catch block.
Personally though I'd mark the function itself as being able to throw the exceptions that you currently catch, and deal with the exceptions at the calling site. Your function then reduces to
private int depth(
Position<Integer> p
) throws InvalidPositionException, BoundaryViolationException
{
return ab.isRoot(p) ? 0 : 1 + depth(ab.parent(p));
}
You have to return from the catch block as well as in the case of an exception, the return statement inside the try block would never be reached.
Your method signature indicates it returns an integer and never fails (doesn't throw any exceptions).
Your implementation is not honoring this contract, if an exception is thrown in your code you catch it, but you don't return any value in that case.
You can fix it in two ways. You can either return an value in your catch block, or you can remove the try catch block and add the exceptions you are catching to your method's signature. Which solution is better depends on what exactly your code does, and how do you think it's going to be used.
Also keep in mind catching exceptions and just logging is a bad practice if you do it carelessly.

Java - How to properly handle a try catch block

I was wondering what is the proper convention for handling a try/catch block. It is pretty obvious what should be within the try block but what about the catch block?
Can I write a message to the user like the following:
do {
try {
System.out.println("Pi to the number of decimal places:");
Scanner in = new Scanner(System.in);
userNth = in.nextInt();
} catch (Exception e) {
System.out.println("Error: Enter a number between 1 and 100");
}
} while(userNth < 1 || userNth > piDecimals);
Or is this bad practice?
Exception-handling is not the place to make rash assumptions; usually by the time this part of your code has been executed it's because something unanticipated has happened, this is when you want to be most careful to be accurate about detecting and recording what happened so that you can tell what needs fixing.
The choice of Exception as the type of exception that gets caught is too broad. The method you're calling throws 3 different exceptions for distinctly different reasons; only one of which is something that should be caught here. Also unchecked exceptions like NullPointerException will get caught by this. If you were to add some code to this catch block that inadvertently introduced a NPE it would be hard to figure out what went wrong. Your overbroad catch can result in bugs not being found or errors not getting handled properly.
(Btw Makoto makes a good point that nextInt isn't what you should be calling here anyway.)
Not logging the exception can be acceptable in narrow cases where you're certain of what the exception means (for instance, if you caught InputMismatchException, or NumberFormatException in Makoto's example code). But in combination with catching Exception it has the capacity to hide errors and cause confusion.
You likely chose to catch Exception because handling a bunch of different checked exceptions, most of which seemed unlikely to ever happen anyway, seemed like an intolerable nuisance. Providing a consistent way of handling and logging exceptions will help, by providing a reasonable default case for exceptions you don't know what to do with. That way if you see an exception you just can't handle, you always have the option of letting it be thrown (possibly catching it and wrapping it in an unchecked exception), knowing that if thrown it will get logged and end your program.
For a very small command-line program sometimes it's entirely ok to let exceptions that you can't handle be thrown from main (by adding throws Exception to the main method). This is ok for toy examples, small school projects, etc.; I'd only use it in production code if there was a plan for logging the output (like a batch file that redirects stderr to a file):
public static void main(String... args) throws Exception {
... application code
}
In most cases all the main method code should be placed in a try block where any Throwable is caught and logged:
public static void main(String... args) {
try {
... application code here
}
catch (Throwable t) {
logger.log(t);
}
}
Either alternative makes it less tempting for you to inappropriately swallow inconvenient checked exceptions.
Simple Answer: what you wrote is fine
Longer Answer: try-catch blocks are for executing code that may throw an exception, and then handling said exception if it occurs. In general, the catch block should have code that handles the exception however you need to handle it. If the statement you currently have is how you want to respond to an exception, then it's fine by convention. Some common things to do in a catch block are:
Throw another exception that encapsulates the thrown exception. (I often do this when parsing so that there can be a single ParseException)
Throw a runtime exception encapsulating the thrown exception and let java's default uncaught exception handler deal with it. (I do this a lot when I'm writing quick temporary programs and I don't want to deal with checked exceptions)
Pass it to some generic handler in your program, such as a GUI to display the error, etc.
call printStacktrace on it
But anything that fits your exception-handling needs is fine
In all actuality, this code is not going to function the way you intend it to. There are two key reasons for this:
nextInt() blocks until it receives an integer; that is, it's not going to care about what input you give it until it reads an integer, and
Even if this were to be okay, depending on how you initialize userNth and piDecimals, one or both of those variables may not be defined, thus preventing compilation.
Also, don't catch Exception. Be as specific as you can when catching exceptions, since Exception also includes some nifty and dangerous RuntimeExceptions like NullPointerException.
What you're looking to do:
Take in an integer input
If the user enters a non-integer, tell them they need to enter an integer
Keep doing this while userNth < 1 || userNth > piDecimals.
To that, we should look to get the right exception thrown by parsing the input as a string first, then as an Integer:
try {
System.out.println("Pi to the number of decimal places:");
userNth = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Enter a number between 1 and 100");
// You have to set this value to something so that userNth is defined!
userNth = Integer.MAX_VALUE;
}
The other part to this is that you have to decide what message you show if userNth > 1 && userNth < piDecimals, since your try...catch isn't going to cover that. This, I leave as an exercise for the reader.

What is the good practice to terminate program in catch clause

I have a method throws an Exception
public int myMethod throws Exception
I have another function calls myMethod function and hava try-catch block.
I throws a runtime exception to enforce the program to be terminated.
Is this a proper way to terminate the program? If I do this way, it prints the stack trace twice and the stack trace from RuntimeException is useless.
What is the suggested way to terminate program in catch clause with printing the full stack trace.
public int callMyMethod(){
try{
myMethod();
}
catch(Exception ex){
ex.printStackTrace(System.out);
throw new RuntimeException();
}
}
The answer is "it depends".
If this code is part of the application itself then calling System.exit(int) is possibly the best option. (But if the application is "failing", then you should call exit with a non-zero return code. Zero conventionally means "succeeded".)
However, if there is a significant possibility that this code is going to be embedded / reused in a larger Java application, calling System.exit(...) is problematic. For instance a library that calls System.exit(...) when something bad happens is going to cause havoc for an application that uses it.
For something like that, you might throw a custom runtime exception which you catch and handle specifically in your main method. (If I was doing that, I'd pass the Exception as a constructor parameter to the custom exception ... and make it the cause exception. And I wouldn't print it / log it at that point.)
(Calling System.exit(...) also causes problems when you are unit testing ... 'cos the call will most likely pull the plug on the JVM running the test suite!)
The other point is that catch (Exception ...) is almost always a BAD IDEA. The point is that this catches just about everything (including all sorts of things that you never dreamed could happen!) and buries them. It is far better to catch the specific exceptions you are expecting (e.g. checked exceptions) and can deal with ... and just let the rest propagate in the normal way.
If you are stuck with catch (Exception ...) because you are using something that is declared as throwing Exception, the best way to deal with it is to change the throws Exception. And the sooner the better. Change the throws Exception to declare a list of (more) specific exceptions that you expect to be thrown by the method.
public int callMyMethod(){
try{
myMethod();
}
catch(Exception ex){
ex.printStackTrace(System.out);
System.exit(0); // terminates with exit code 0, no extra stack trace.
}
}
Exception handling is one of the most important aspects in programming.
The answer for your question depends on what type of application you are working on.
system.exit(0) will just terminate your program and this can create a lot of havoc .
Also make sure that you never catch Exception , if you are doing that then you are catching all the types of exceptions which you may not intend to handle also.
Always catch Specific exception such that it gives you opportunity to handle it in a manner which you need.

Java - Difference between throwing an Exception and catching and rethrowing Exception

I'm confused as to what the beneift would be in catching and rethrowing an exception versus just throwing it in the first place.
For example
private void testMethod() throws Exception
{
//some bad code here
}
versus:
private void testMethod() throws Exception
{
try
{
//some bad code here
}
catch (Exception e)
{
throw e;
}
} //end testMethod()
Is this to preserve the stack trace of the error message? I tried setting up an example, but didn't see any different output between the two.
Thanks for the help.
There is no difference in behaviour between your two code samples. (In particular, stacktraces are recorded when an exception is created, not when it is thrown, so a rethrown exception will still have the original stack trace). Usually, people therefore use the simpler idiom.
That is not to say rethrowing doesn't have its uses. For instance, if you wanted to handle all exceptions except FooBarExceptions, you could write:
try {
// bad code
} catch (FooBarException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
Or if the decision to handle an exception is more involved than simply checking its type, you can simply catch it, and rethrow if it turns out you can't handle it:
for (int attempts = 0; attemps < 6; attempts++) {
try {
return crankyMethod();
} catch (Exception e) {
if (fatal(e)) {
throw e;
} else {
// try again
continue;
}
}
}
It is worth noting that when people say rethrow, some mean to throw a different exception, as in the following example:
for (int i = 0; i < array.length; i++) {
try {
process(array[i]);
} catch (Exception e) {
throw new RuntimeException("Could not process element at index " + i, e);
}
}
The advantage of this pattern is to decorate the original exception with additional information that might be relevant (in the above example: what data could not be processed). Note that the original exception is passed to the constructor of the new one, so its stack trace is not lost.
As others have said, in your example there is no difference, and the 2nd form should be avoided.
The only place where it sometimes makes sense is where you need to catch some exceptions, and let others get thrown upwards. Because Java's exception handling syntax is limited, sometime you might do this:
try {
somePieceOfCode();
} catch( RuntimeException e ) {
throw e;
} catch( Exception e ) {
handleException(e);
}
This is sometimes done if somePieceOfCode throws a number of different checked exceptions that don't have a common base class (other than Exception) but need to be handled in the same way. You might not want to just catch Exception because that would also catch things like NullPointerException, and you might prefer for those exceptions to bubble up as-is.
This code will let all RuntimeExceptions bubble upwards, but handle all other exceptions.
This idiom is little unusual, and not everyone likes it, but you might see it in some places.
With this approach you are able to modify the Exception. For example you could give it a more specific message.
With this said, you should generally don't use this technique because
It clusters up your code for no additional benefit (under normal circumstances)
You should only use try-catch blocks where actually necessary because it can slow down execution
The standard reasons to catch and rethrow an exception are:
To log the incident and the exception.
To do some cleanup due to the exception (but often better done in a finally block).
To wrap the exception in a more appropriate exception (I.e. it is probably more appropriate for your processAccount() method to throw an AccountException (or some such) instead of a DbException).
There is no difference. Unless you want to do something with it (the exception) before re-throwing it.
I don't think there is much of a difference, but for what it's worth I'd prefer the first one.
You should not catch an exception unless you can do something about it OR if your class is a boundary beyond which no exception should propagate (e.g. a web controller that catches all exceptions and routers users to friendly error pages).
Simply catching and rethrowing is a waste of keystrokes. It adds no information and does nothing constructive.
The one exception would be to catch a checked exception and wrapping it as an unchecked exception. Otherwise avoid the second idiom.
One of the main benefits of catching then rethrowing is to wrap an exception in another, domain specific exception, so the calling code does not have to worry about implementation specific issues, and can just catch a library specific exception.
There is no real benefit in the example you have given, however a good example of such a benefit can be seen in other libraries - as an example we can look at Hibernate.
Hibernate catches the generic SQLException, and then examines the object to determine the real cause of the exception, before wrapping it in a Hibernate specific exception which is more descriptive of what the issue was in the first place.
However, if you are just catching an exception and throwing the same exception, then you are most likely to do it so you can log the exception in the first place (although this isn't necessarily the best approach to use).

Try-catch: is this acceptable practice?

We have received Java code from a software supplier. It contains a lot of try-catch blocks with nothing in the catch part. They're all over the place. Example:
try {
spaceBlock.enable(LindsayModel);
} catch (Exception e) {
}
My questions are: Is the above acceptable practice? If so, when? Or should I just go ahead and remove all of these "bogus" try and catch statements?
To me this looks like terrible practice, but I'm not experienced enough in Java to tell for sure. Why catch errors if you're not going to do anything with them? Seems to me, you would only do that if you were confident that an exception would be of absolutely no consequence and you don't care if one occurs. However, this is not really the case in our particular application.
EDIT To give some context: We bought a Java-scriptable product from the supplier. Alongside the product, they provided a large proof-of-concept script tailored to our needs. This script came "free of charge" (though we wouldn't have bought the product if it hadn't come with the script) and it "works". But the script is a real pain to build upon, due to many things that even I as a Java novice recognise as awful practice, one instance being this bogus try-catch business.
This is indeed terrible practice. Especially the catching of Exception rather than something specific gives off a horrible smell - even a NullPointerException will be swallowed. Even if it is assured that a particular thrown exception is of no real consequence, one should always log it at the very least:
try {
// code
}
catch (MyInconsequentialException mie) {
// tune level for this logger in logging config file if this is too spammy
MY_LOGGER.warning("Caught an inconsequential exception.", mie);
}
However it is unlikely an exception is completely meaningless in this situation. I recommend researching exactly what exception(s) the application's code is intending to swallow here, and what they would really mean for the execution.
One important distinction is whether the try/catches are used to swallow checked exceptions. If this is the case, it probably indicates extreme apathy on the programmer's part - somebody just wanted his/her code to compile. At the least, the code should be amended:
try {
// code
}
catch (SpecificCheckedException sce) {
// make sure there is exception logging done farther up
throw new RuntimeException(sce);
}
This will rethrow the exception wrapped in an unchecked RuntimeException, effectively allowing the code to compile. Even this can be considered a bandaid however - best practice for checked exceptions is to handle them on an individual basis, either in the current method or farther up by adding throws SpecificCheckedException to the method signature.
As #Tom Hawtin mentioned, new Error(sce) can be used instead of new RuntimeException(sce) in order to circumvent any additional Exception catches farther up, which makes sense for something that isn't expected to be thrown.
If the try/catch is not being used to swallow checked exceptions, it is equally dangerous and should simply be removed.
Terrible, indeed. Swallowing an exception like this can be dangerous. How will you know if something bad has happened?
I'd feel better if the vendor wrote comments to document and acknowledge it ("We know what we're doing"). I'd feel even better if there was a strategy apparent in the code to deal with the consequences. Wrap it in a RuntimeException and rethrow; set the return value to an appropriate value. Anything!
"All over the place"? Are there multiple try/catch blocks littering the code? Personally, I don't like that idiom. I prefer one per method.
Maybe you should find a new vendor or write your own.
try {
meshContinuum.enable(MeshingModel);
} catch (Exception e) {
}
This looks like unfinished code. If the enable method throws an Exception then it will be caught and swallowed by the code. If it doesn't then it does not make sense to try to catch a non occuring exception.
Check to see the methods and where their signatures are not followed by throws exceptionName, then remove the empty try-catch statements from the places they are called.
You can theoretically put try-catch around any statement. The compiler will not complain about it. It does not make sense though, since this way one may hide real exceptions.
You can see this as a sign of bad code quality. You should probably be prepared to run into problems of different type too.
It's not the best:
It hides evidence of the exception so debugging is harder
It may cause features to fail silently
It suggests that the author might actually have wanted to handle the exception but never got around to it
So, there may be cases where this is OK, such as an exception that really is of no consequence (the case that comes to mind is Python's mkdirs, which throws an exception if the directory already exists), but usually, it's not so great.
Unfortunately you cannot just remove it, because it the try block throws a checked exception then it will have to be declared in the throws clause of the method. The callers of the method will then have to catch it (but not if the callers also have this catch (Exception e) {} abomination).
As an alternative, consider replacing it with
try {
meshContinuum.enable(MeshingModel);
} catch (Exception e) {
throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
}
Since RuntimeException (and classes that extend it) are unchecked exceptions they do not need to be declared in the throws clause.
What did your contract with the supplier specify? If what they wrote, bad practice and all, meets the spec then they will charge you for a rewrite.
Better to specify a set of tests that will enter many or all of those try-catch blocks and hence fail. If the tests fail you have a better argument to make them fix their terrible code.
Horrible idea on the face of it, totally depends on what you're actually calling. Usually it's done out of laziness or habituated bad practices.
Actually ... not so fast.
There are legitimate cases for ignoring an exception.
Suppose that an exception has happened already, and we're already in a catch(). While in the catch(), we want to make best effort to clean up (which could fail, too). Which exception to return?? The original one, of course. The code looks like this:
try {
something-that-throws();
} catch(Exception e) {
try {
something-else-that-throws();
} catch(Exception e1) {}
throw e;
}
When we really don't care whether an operation succeeds, but (unfortunately) the operation's author throws an exception if a failure occurs.
if (reinitialize) {
try {
FileUtils.forceDelete(sandboxFile); // delete directory if it's there
} catch(Exception e) {}
}
The above saves a rather tortured attempt to see if sandboxFile actually exists before deleting it anyway.

Categories

Resources