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.
Related
So my custom exception is PatternFormatException, and I've appended throws PatternFormatException, to the end of my method, but I'm wondering how I can actually get the method to physically throw it? Do I use if statements? i.e.
if //[doesn't_parse] throw PatternFormatException
This seems cumbersome for many different lines of code? Can I catch a more universal in built exception i.e. NumberFormatException, and then in the handling of this, throw my own exception?
You throw an exception using the throw keyword:
throw new PatternFormatException(...);
Generally you want to catch exceptions as early as they occur and handle them properly. If you want your parser (or whatever program you are writing) to generate meaningful errors, it's usually a good idea to wrap any caught exception and re-throw it, embedded in a more meaningful exception, giving the user a better idea of how things went wrong.
Something like this:
try {
doSomething(); // throws SomeException
doSomethingElse(); // throws SomeOtherException
}
catch (Exception e) {
throw new PatternFormatException(..., e);
}
generally is fine, if you know exactly what exceptions might happen and if all of them are properly encapsulated by PatternFormatException. However, the key idea of Exceptions in Java is that you are always aware of all the possible Exceptions that can happen. That is why Java forces you to add all possibly thrown Exceptions (except for RuntimeException) to the method declaration.
A safer design would be:
try {
doSomething(); // throws SomeException
doSomethingElse(); // throws SomeOtherException
}
catch (SomeException e) {
throw new PatternFormatException(..., e);
}
catch (SomeOtherException e2) {
throw new PatternFormatException(..., e2);
}
catch (Exception e3) {
throw new UnexpectedPatternFormatException(..., e3);
}
Note that the first two catches call different constructors, and thus can handle different Exceptions differently. The last catch wraps an unexpected exception because your program encountered an exception (probably a RuntimeException) that you did not plan for. If users then complain about UnexpectedPatternFormatException, you can just go back to your code and fix the code so that the underlying Exception either does not get thrown anymore or gets wrapped in a more meaningful way. You can also just use a single UnexpectedMySomethingException class as the fall-back for all try/catch blocks that you have, to keep things a bit simpler.
One last word should be said about issues caused by Exceptions: Even though, Java uses Exceptions for all kinds of situations, even those that are largely not in the control of the Java programmer (e.g. when accessing files or even trying to parse strings as numbers), always be aware that throwing and catching Exceptions is actually quite expensive, which is why many people tend to avoid that. Only really use Exceptions, if performance is not of an issue (when the Exception is a rare event).
Also, Exceptions can threaten the integrity of your program's state if you throw an Exception and catch it too late, so that lines that should have been executed did not get executed (e.g. code for cleaning up resources or other code that is needed to keep the program state "correct"), and, as a result, the only safe thing to do is to shut down the program.
If I understand your question correctly you could just do this:
If(somethingBad){
throw new PatternFormatException();
}
As stated in a response below. If your going to check this exception over and over again you might want some Static Method/Class Method (use your programming brain). For example you could do something like:
void checkForException(String pattern, String check){
If(!check.equals(pattern)){
throw new PatternFormatException();
}
}
Now all you have to do is:
try{
checkForException("abc","123");
}catch(PatternFormatException pfe){
System.out.println(pfe); //Whatever you want to happen if the exception is thrown
}
Remember though, ONLY use exceptions for exceptional situations...
Have a read over this for more information on exceptions. I find that I next to never use exceptions.
This question already has answers here:
Try-catch: is this acceptable practice?
(8 answers)
Why are empty catch blocks a bad idea? [closed]
(20 answers)
Closed 9 years ago.
Say I have a try statement with and empty catch is that bad practice? For example say I have 2 try separate trys where it is possible for one to fail but the other to succeed or both succeed or any possible combination of such. Is that bad practice to handle code like that?
Example
if( mode == Modes.EDIT ){
try {user = userBo.findById(id).get(0); }
catch(Exception e) { }
try{
result = this.initializeEntityById(accountDao, id);
if( !result.equals(SUCCESS) ){
return result;
}
}
catch(Exception e){ }
}
In this example the variable in concern is 'id' where I'm not sure if the value coming in is valid and on the front end it doesn't really matter because the code handles whatever comes in and provides correct display.
So the question really is:
Is this a bad practice with the empty catch's?
Is there any potential instability that could occur that I'm not realizing?
Is there a better way to achieve what I'm looking to get at?
Yes it's always bad practice since you have no idea what went wrong where. You should at least log the exception.
The instability is that when something goes wrong, you have no idea what is wrong with your code.
It's never desirable to use exceptions for control-flow. The performance is atrocious, and exceptions should only be used for exceptional circumstances. Here's what you can do:
Make the exception part of the method signature and let a higher level handle it.
Catch the exception, but wrap it in a semantically-appropriate exception and rethrow it so a higher level can handle it.
Handle it. This can also be done in multiple ways:
Don't let the exception happen: instead of catching the exception, perform an inspection on the data to see if it can cause an exception. For example, in your case I think you should have a method like userBo.existsWithId(id) which will return a boolean that says whether the user exists. Or have the findById return null if the user cannot be found, and check to see if user == null. I think this is your best bet.
Recover from the exception in some sane way (depends on your business logic).
This is bad practice.
There's no instability, per se, but with empty catches, nothing is being done about the exception, which could leave an object in an inconsistent state if some aspects didn't get processed due to the exception.
With that said, empty catch blocks make for very difficult debugging. Even in production code, you should include a basic "notification" for most exceptions.
In testing code, use e.printStackTrace( in every catch block that does nothing otherwise.
1) Is this a bad practice with the empty catch's?
Yes this is not a good practice.
2) Is there any potential instability that could occur that I'm not realizing?
If you anything goes wrong and any exception thrown then you will not be able to identify what goes wrong because in catch block you are not doing anything so it is assumed to be handled.
3) Is there a better way to achieve what I'm looking to get at?'
Try to log the exception stacktrace in catch block . or throw it again
e.g. e.printstacktrace();
Yes, this is bad practice.
If an exception is thrown, it should be handled somehow, and the catch block is meant to hold the handling code. At the very least, if you don't need recovery code and alternate logic in your method to handle a caught exception (which would be rare), you should log the exception so you know it happened.
You can read an excellent article on handling exceptions here:
http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2
I found the second page to be especially helpful.
I am checking out the new features of Java SE7 and I am currently at this point:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
regarding the catch multiple feature, when I came across this statement:
Note: If a catch block handles more than one exception type, then the
catch parameter is implicitly final. In this example, the catch
parameter ex is final and therefore you cannot assign any values to it
within the catch block.
I never noticed that the caught exception is not final in the classic case of handleing caught exceptions.
I just wonder why is that a good thing in the first place? Would it not be ill-advised to essentially MODIFY a caught exception before I guess rethrowing it or maybe logging it's message? Should it not be up to the trowing mechanism to create the exception so it represents exactly what it should?
I have never seen an exception being modified in the catch block can maybe someone point out it's benefits?
It's pretty much the same as method arguments:
You usually don't modify them and many people agree that they should be treated as final (whether or not to actually write final in front of them is a matter of some debate).
But since there's no technical requirement that says it must be final, the language gives you the option to choose.
Personally I know of no good reason to modify the exception reference of a catch-block.
I cannot think of a convincing use-case for modifying an exception in a classic catch clause. However, that doesn't mean it should be forbidden. Especially given that you can modify a parameter variable. If you find this worrisome, you have the option of declaring the exception variable to be final.
On the other hand, allowing modification in the multi-exception catch would introduces the possibility of truly bizarre and confusing code such as this:
catch (IOException | NullPointerException ex) {
...
ex = new IllegalArgumentException(...);
}
I imagine that's what the designers had in mind when they added the restriction in this case.
But either way, this is how the Java language is defined, and what we have to live with. There's not a lot of point in debating the apparent inconsistencies ... unless you are intending to design and implement a new language.
The reason I can think of to enforce it final is due to performance. Once the catch evaluation starts, having a final immutable value in the mechanics of the evaluation ensures a faster evaluation of all catches. Since try-catch is extensively used throughout any java code, the highest performance design is preferable.
Based on the above, it implies a performance improvement that affects most programs.
The idea behind exception-based error handling is that each error should be recovered, if at all possible, at the appropriate level of abstraction. Such error recovery might require information that is not directly available where the exception is actually handled. For this reason it might be convenient to catch the exception, augment it with the relevant information and rethrow it or possibly set it as cause of a new exception object of a more appropriate class.
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.
I have a piece of code that encodes some kind of business data in a JSON string:
public String encodeDataAsJsonString(Data data) throws JSONException {
JSONObject o = new JSONObject();
o.put("SomeField1", data.getSomeProperty1());
o.put("SomeField2", data.getSomeProperty2());
...
return o;
}
The thing is:
JSONException is a checked exception, but
I don't really know how to handle it at compile time. If a JSONException really occurs, it's probably a bug in the the code and should be handled by the regular "global uncaught exception handler" which is already there (e.g. this), and which already performs all the necessary logging and cleaning up.
Thus, I ended up doing this in the calling method:
...
try {
encoded = encodeDataAsJsonString(data);
} catch (JSONException e) {
throw new RuntimeException(e);
}
...
It seemed like a lesser evil than adding a throws JSONException to every method up the call stack. However, it still feels dirty, hence my question:
If I want some specific checked exception to go the "regular unchecked exception route", is rethrowing it as a RuntimeException the correct idiom to use?
The situation is quite simple: if your exception has no business value, that is, it is just a failure, definitely use an unchecked exception. If you need to handle the exception in a way specific to that exception, which in most cases means that the handling code will involve business logic, then it is still OK to use an unchecked exception, but there are at least some benefits in using a checked exception. However, in either case the raw exception you get from the JSON API is useless and it is only a sign of bad public API design.
As a side note, there's the "sneaky throw" idiom which will allow you to throw your original checked exception without wrapping:
public static <R> R sneakyThrow(Throwable t) {
return UncheckedThrower.<RuntimeException, R>sneakyThrow0(t);
}
#SuppressWarnings("unchecked")
private static <E extends Exception, R> R sneakyThrow0(Throwable t) throws E { throw (E)t; }
Needless to say, you should be very careful about using this approach in a project.
Short answer, yes.
You could probably create your own exception class (a child of runtime exception) and re throw that to make it easier to document, catch/ handle it where necessary. Something like hibernate does by using HibernateException, client/ calling code is not forced to catch it but can always catch it when something logical/ application specific can be done with it.
Well, if you don't intend to handled the exception in you application code then you can throw it as RuntimeException.
I prefer to use com.google.common.base.Throwables to propagate this.
There is an argument for using only unchecked exception in your Java code. If you want to follow that approach, wrapping checked exception them as you have done is the only sensible thing to do. FWIW, I have used this approach many times and it has been useful.
Even if you don't want to buy in to that style it may be still be useful to convert some checked exceptions to runtime exceptions.
I do this all the time. Yes it is a good approach to do it. No, it is not a dirty approach. Personally, I cant stand checked exceptions. I wrap all checked exceptions as runtime exceptions regardless of what type of exception it is.
Checked exception is a way to communicate between developers. Checked exceptions says "handle me". If you know what you do, you can rethrow exceptions (and log).
EDIT: as in other answer rewrap exception is also good advice.