I have designed a uploaded file handling as follow:
The UploadFileHandler is the main class providing checking methods.
public class UploadedFileHandler {
public static void handleUploadedFile(String fileName) {
try {
checkFile(fileName);
} catch (BadUploadedFileException ex) {
deleteFile(fileName);
}
}
private static void checkFile(String fileName) {
new UploadedFileChecker(fileName).check();
}
private static void deleteFile(String fileName) {
//...code to delete the file.
}
}
And the UploadedFileChecker do the checking.
public class UploadedFileChecker {
private String fileName;
public UploadedFileChecker(String fileName) {
this.fileName = fileName;
}
public void check() throws BadUploadedFileException {
checkFileFormat();
scanVirus();
}
private void checkFileFormat() {
// if file format unsupported
throw new BadUploadedFileException();
}
private void scanVirus() {
// if contains virus
throw new BadUploadedFileException();
}
}
And the BadUploadedFileException is declared as follow:
public class BadUploadedFileException extends RuntimException {
}
I let it extend RuntimeException because it makes the code in UploadedFileChecker clean, but doing this make it an unchecked exception. Thus, the catch in handleUploadedFile is inapproriate since we should not catch unchecked exceptions.
My question is, should I catch the BadUploadedFileException or make it extends Exception and append "throws BadUploadedFileException" to every method of UploadedFileChecker.
Exceptions should be used for exceptional conditions. Things that you don't expect to happen.
You shouldn't use them for conditional logic.
Josh Bloch outlines that specifically in his book, which is quite good and a must-have IMHO:
http://java.sun.com/docs/books/effective/
since we should not catch unchecked exceptions.
There is no such rule. You catch any exceptions whenever you know what to do with it.
However, one must never catch Errors!
I think you'd be better off making check() return a boolean.
I believe that'll make the code look cleaner, and like Brian said- exceptions aren't really for logic- they're for when something goes unexpectedly wrong.
are you going to do anything if you get an exception? If not, let it bubble. If you are then you can certainly catch an uncheck exception.
Personally, I think it should be a checked exception. You should prob. throw it from each file handling method and catch it in UploadedFileHandler, handling it appropriately, if you need different handling logic then split BadUploadedFileException into a number of different types of exceptions.
More information on checked and unchecked exceptions here.
The last option would be preferable. I don't think it makes the code much harder to read, and at least you (and your colleagues in upcoming versions) will be remembering to handle it.
Besides that, it is certainly not forbidden to catch Exceptions derived from RuntimeException. Catching RuntimeException or Exception on the other hand should only be done in main methods and suchlike (it could be an OutOfMemoryException!).
If you use explicit RuntimeExceptions, don't use a "throws" keyword in the method specification but do include them in the JavaDoc if they seem important.
Related
Are these code statements equivalent?
Is there any difference between them?
private void calculateArea() throws Exception {
....do something
}
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
Yes, there's a huge difference - the latter swallows the exception (showing it, admittedly), whereas the first one will let it propagate. (I'm assuming that showException doesn't rethrow it.)
So if you call the first method and "do something" fails, then the caller will have to handle the exception. If you call the second method and "do something" fails, then the caller won't see an exception at all... which is generally a bad thing, unless showException has genuinely handled the exception, fixed whatever was wrong, and generally made sure that calculateArea has achieved its purpose.
You'll be able to tell this, because you can't call the first method without either catching Exception yourself or declaring that your method might throw it too.
They differ in where the responsibility to deal with the Exception lies. First one just throws Exception, so it does not handle it. The code that calls the method needs to handle the Exception. Second one catches and handles the Exception within the method, so in this case the caller doesn't have to do any exception handling, provided showException() itself does not throw another exception.
Yes. The version which declares throws Exception will require the calling code to handle the exception, while the version which explicitly handles it will not.
i.e., simply:
performCalculation();
vs. moving the burden of handling the exception to the caller:
try {
performCalculation();
catch (Exception e) {
// handle exception
}
Yes, there is a great deal of difference between them. The in the first code block, you pass the exception to the calling code. In the second code block you handle it yourself. Which method is correct depends entirely on what you are doing. In some instances, you want your code to handle the exception (if a file isn't found and you want to create it, for instance) but in others, you want the calling code to handle the exception (a file isn't found and they need to specify a new one or create it).
Generally speaking as well, you don't want to catch a generic exception. Instead, you'll want to catch only specific ones, such as FileNotFoundException or IOException because they can mean different things.
There is one particular scenario where we cannot use throws, we have got to use try-catch.
There is a rule "An overridden method cannot throw any extra exception other than what its parent class is throwing". If there is any extra exception that should be handled using try-catch.
Consider this code snippet.
There is a simple base class
package trycatchvsthrows;
public class Base {
public void show()
{
System.out.println("hello from base");
}
}
and it's derived class:
package trycatchvsthrows;
public class Derived extends Base {
#Override
public void show() {
// TODO Auto-generated method stub
super.show();
Thread thread= new Thread();
thread.start();
try {
thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// thread.sleep(10);
// here we can not use public void show() throws InterruptedException
// not allowed
}
}
When we have to call thread.sleep() we are forced to use try-catch, here we can not use:
public void show() throws InterruptedException
because overridden method can not throw extra exceptions.
If you threw an exception, the child method (which overrides this) should handle the exception
example:
class A{
public void myMethod() throws Exception{
//do something
}
}
A a=new A();
try{
a.myMethod();
}catch Exception(e){
//handle the exception
}
I assume that by "identical" you are referring to behavior.
A behavior of a function can be determined by:
1) Returned value
2) Thrown exceptions
3) Side effects (i.e changes in the heap, file system etc)
In this case, the first method propagates any exception, while the second throws no checked exception, and swallows most of the unchecked exceptions as well, so the behavior IS different.
However, if you guarantee that "do something" never throws an exception, then the behavior would be identical (though the compiler will require the caller to handle the exception, in the first version)
--edit--
From the point of view of API design, the methods are completely different in their contract. Also, throwing class Exception is not recommended. Try throwing something more specific to allow the caller to handle the exception better.
Many times you want the caller to handle the exception. Let's say you have the caller call a method which calls another method which calls another method, instead of having each method handle the exception, you can just handle it at the caller. Unless, you want to do something in one of the methods when that method fails.
The caller of this method will need to either catch this exception or declare it to be rethrown in it's method signature.
private void calculateArea() throws Exception {
// Do something
}
In the try-catch block example below. The caller of this method doesn't have to worry about handling the exception as it has already been taken care of.
private void calculateArea() {
try {
// Do something
} catch (Exception e) {
showException(e);
}
}
private void calculateArea() throws Exception {
....do something
}
This throws the exception,so the caller is responsible for handling that exception but if caller does not handle the exception then may be it will given to jvm which may result in abnormal termination of programe.
Whereas in second case:
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
Here the exception is handled by the callee,so there is no chance of abnormal termination of the program.
Try-catch is the recommended approach.
IMO,
Throws keyword mostly used with Checked exceptions to convince
compiler but it does not guarantees normal termination of program.
Throws keyword delegate the responsibility of exception handling to
the caller(JVM or another method).
Throws keyword is required for checked exceptions only ,for unchecked
exceptions there is no use of throws keyword.
I am unsure how best to structure custom exceptions. Say i have a situation where there's some library that throws its own custom exception class, with a custom field in it:
public class CustomException extends RuntimeException {
private final String additionalInfo;
public CustomException(String message, String additional) {
super(message);
this.additionalInfo = additional;
}
public String getAdditionalInfo() {
return additionalInfo;
}
}
Dealing with this is pretty straightforward:
try {
something();
} catch (CustomException e) {
LOGGER.error(e.getMessage());
LOGGER.error(e.getAdditionalInfo());
}
So far, so good, but what about when this is wrapped up many layers deep into some sort of service and handled in this way:
// in a subclass of a theoretical ServiceHandler interface
public void handle() throws OperationFailedException {
try {
something();
} catch (RuntimeException e) {
throw new OperationFailedException("The operation failed.", e);
}
}
Further down the callstack the service dispatch code catches this new exception, returns the generic (safe) message to the external caller, and logs the full exception trace somewhere internal, including the cause (our original custom exception type). The problem now is that the extra field in CustomException has gone missing from the logs, because the logging framework is only interested in getMessage() and the callstack.
try { // call to the ServiceHandler
sendResponseToClient(findServiceHandler(rpcName).handle(args));
} catch (Throwable th) {
LOGGER.error(th);
sendErrorToClient("An internal error occurred with incident ID: <id>");
}
I can think of a few of solutions:
1) Make the thing that logs the service exceptions aware of this special exception type so it can log it
2) Override getMessage() so it returns super.getMessage() + getAdditionalInfo()
3) Everywhere something is called that could throw one of these i rethrow it as something else with the additional field baked into the message:
try {
something();
} catch (CustomException ce) {
throw new OperationFailedException("The operation failed because " + ce.getAdditionalInfo(), ce);
} catch (RuntimeException e) {
throw new OperationFailedException("The operation failed", e);
}
The actual use case is a native code library with a few hundred functions, and they're called literally everywhere throughout this app. This exception type is a general "the api has failed in an unexepected way" error, so it's unchecked, and in day to day operation i wouldn't expect to ever see one.
(1) seems like it's easy to miss out new types in future, if in a year's time someone adds another custom exception type they need to be aware of all places that might log it and write the corresponding handler code there. (2) feels a little fishy, since you'd be creating an exception with one message, and getting a different message back. Applying the pattern in (3) to it seems like it will produce a lot of clutter, particularly if i have a couple of these custom exception types to worry about.
Which approach should i use? Are there other options, or would you recommend restructuring something to get around this?
There are essentially two cases for an exception:
1) You can recover
2) You can't, you just want your application to exit
If you can recover, you may want to think about using a checked exception.
Then you have to deal with the exception and the compiler will tell you where to catch it.
Otherwise, if the application just crashes you may want to add this additional info to the message you're giving to the superclass constructor.
I'm beginner in Java and Android. My problem is when I use setDefaultUncaughtExceptionHandler in my code, some functions still need a try/catch block surrounding it, but I want throw all my exceptions to UncaughtException thread.
public class MyAlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(context));
try
{
String imageURL = MyWebService.readFeed();
DownloadAndSet.downloadFile(imageURL);
}
catch(Throwable e)
{
throw new RuntimeException(e);
}
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
}
Java distinguishes checked and unchecked exceptions. Checked Exceptions have to be caught, no matter what.
Correction: Or you have to add the throws clause to the method. This postpones the urge to catch that exception to the caller of your method.
If you want them to be handled in the UncaughtExceptionHandler, you can "forward" them:
try{
// blah "throws some checked exception type"
} catch ( Throwable e ) {
// throw e; <- This will not work :( unless you add the "throws" clause.
throw new RuntimeException(e);
}
Unfortunately, just throwing the same Exception won't work, because you'd have to add the throws clause, which you do not want. You'll have to wrap it in a RuntimeException.
All checked exceptions in your code must be caught.
Further reading on checked vs unchecked exceptions:
http://www.javapractices.com/topic/TopicAction.do?Id=129
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
When you call a method that throws an exception, requires you to either handle the exception using try/catch or throw the same exception.
As you don't want to handle the exception in your code and want all exceptions to be handled by your Default Exception handler so you need to add throws to all your methods where you don't want to catch the exception.
The documentation says:
Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.
It doesn't relate to exceptions you have to catch. An example of an exception you have to catch/throw is IOException. An example of an exception you don't is NullPointerException.
So if your code causes a NullPointerException, the default handler will deal with it. If your code (potentially) causes an IOException, you have to deal with it then and there (either by catching or throwing).
What I have always done in my programs is create a exception handler method and call it every time I make a try/catch block. Many times I have had Thread.sleep() methods and I just send the exception to a common place to do "global" handling. In your global exception handler, you can also refer to this method.
Keep in mind that you might not always want to use this method because things like file streams might throw errors if a file already exists and you would want to take a different approach such as naming it something else than just stopping the program.
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
catchException(e);
}
});
try {
Thread.sleep(1000);// Just an example of a possible exception thrower
}
catch (InterruptedException e) {
catchException(e);
}
}
public static void catchException(Throwable e) {
// Deal with the exception here
System.out.println("Oh no! You broke the program!!!");
System.out.println("Here is the error btw: " + e.getMessage());
}
If you are using Eclipse, you can set the default automatic code generation for try/catch blocks to automatically include this method:
You can also set project specific settings if you don't want this behaviour for all of your projects.
I have some private method in a class which has equal exception handling. Their body code raises equal exception types and the code handling is the same.
private void method1() {
try {
//make_the_world_a_better_place
}
catch(IOException ioe) {
// ...
}
}
private boolean method2(String str) {
try {
//make_a_cheesecake
}
catch(IOException ioe) {
// ...
}
}
Which is the best way to externalize the common exception handling, so when I make a change in the exception handling code of one of the methods the change will propagate to other methods? Template Method pattern would be handy in this situation, but I don't want go deep into the class hierarchy.
EDIT: There are several catch clauses, not only one like in the example.
Create an interface:
public interface Executor {
void exec() throws Exception;
}
in your class:
checkForExceptions(new Executor() {
#Override
public exex() throws Exception {
method1();
}
});
private void checkForExceptions(Executor ex) {
try {
ex.exec();
} catch (Exception e) [
/// handling
}
Your instinct is good - DRY is a good thing. But don't do this. Your code will be harder to read.
Make sure your catch blocks are really handling the exception and not just swallowing it. If your class isn't providing remediation, I'd say it'd be better to throw it and let clients figure out what to do.
You can create a handleException(IOException ioe) method which they both call.
I was thinking for a try-catch-handling at one place and the method's logic between them, but I guess the world then would be too perfect. Actually I have several catch clauses in the methods.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Best practices for exception management in JAVA or C#
I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.
So, my question is what is the best practice to handle exceptions to produce clean and high quality code.
Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear!
I've tried to keep in mind testability and same abstraction level in methods.
Every constructive comment is welcomed. :)
import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
/**
* <p>This is a dummy code.</p>
* The aim is present the best practice on exception separation and handling.
*/
public class ExceptionHandlingDemo {
// System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);
// instance of cannot work with List<Point>
private interface PointList extends List<Point> {}
/**
* The method that loads a list of points from a file.
* #param path - The path and the name of the file to be loaded.
* Precondition: path cannot be {#code null}. In such case {#link NullPointerException} will be thrown.
* Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {#code null}.
* */
/* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
public List<Point> loadPointList(final String path) {
Preconditions.checkNotNull(path, "The path of the file cannot be null");
List<Point> pointListToReturn = null;
ObjectInputStream in = null;
try {
in = openObjectInputStream(path);
pointListToReturn = readPointList(in);
} catch (final Throwable throwable) {
handleException(throwable);
} finally {
close(in);
}
return pointListToReturn;
}
/*======== Private helper methods by now ========*/
private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
return new ObjectInputStream(new FileInputStream(filename));
}
private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
final Object object = objectInputStream.readObject();
List<Point> ret = null;
if (object instanceof PointList) {
ret = (PointList) object;
}
return ret;
}
private void handleException(final Throwable throwable) {
// I don't know the best practice here ...
logger.error(throwable.toString());
}
private void close(final Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
logger.error("Failed closing: %s", closeable);
}
}
}
/*======== Getters and setters by now. ========*/
// ...
/**
* #param args
*/
public static void main(String[] args) {
ExceptionHandlingDemo test = new ExceptionHandlingDemo();
test.loadPointList("test-filename.ext");
}
}
EDITED:
What I want to avoid is writing lot of catch cases after each other...
A few suggestions at first glance:
You shouldn't catch Throwable and instead catch as specific of an exception as possible. The trouble with catching Throwable is that will include Error classes like OutOfMemoryError and the like. You want to let those pass through (they're unchecked for a reason).
When you log exceptions always pass the exception and not just its toString(). It's very hard to diagnose problems without the stack trace.
You probably don't want a general exception handling method.
So at places you catch exceptions you want something like this:
} catch (IOException e) {
logger.error("some relevant message", e);
// now handle the exception case
}
The message should include some contextual information if possible. Anything that might help tracking down the problem when someone is hunting through logs.
For checked exceptions that I'm not going to bother, I always use org.apache.commons.lang.UnhandledException.
For example
/**
* Calls Thread.sleep(millis)
*/
public static void threadSleep(final long millis) {
try {
Thread.sleep(millis);
} catch (final InterruptedException e) {
throw new UnhandledException(e);
}
}
Always catch the most specific exception possible--in otherwise never catch throwable.
The most important thing to me is that you NEVER have an empty catch block--one of these can take an amazing amount of time to find if something inside the try actually throws an exception.
I personally like to remove checked exceptions as quickly as possible and replace them with pre/post condition checks if possible. Same with unchecked exceptions to a lesser degree--however unchecked exceptions are actually a pretty good way to indicate programmer error like parameter checking to ensure object state (Although asserts may be better yet)
There some options you can choose.
One of the most important adnvantages of exceptions using is that you can have the only exception handler for all cases. When you write your code you should think about functionality first and only then about exception handling. As a result you may skip in some places try/catch at all for unchecked exceptions and declare your methods as throws SomeCheckedException for checked exceptions. This allows you to have the minimum number of exception handlers.
If you don't know what exactly to do with an exception, just rethrow it.
If you catch checked exception but you don't want clients that use your code have to process exceptions, you may checked exceptions update into unchecked. (Hibernate processes exceptions by this way. They catch checked sql exception and throw unchecked exceptions instead of this)
If the previous recommendation are not convenient for your, then you may also choose some options:
you may just add logging and rethrow the same exception
you may use exception chains by throwing new exception with initCause() method
you may think that code that invokes your code should not know anything about the originial exception, you may archive this either by creating new exception or by using fillInStackTrace() method.
Concerning catching Throwable. Yes in the methods you should not catch it. But as a rule the client that uses your programe need not to see excetpions at all, as a result, you may catch Throwable in the some exception handler that is the top in the chain.