Re-throwing runtime exceptions as checked exceptions - java

Should one re-throw a runtime exception as a checked exception, where a client could sensibly anticipate and handle the situation.
It seems to me that is the purpose of checked exceptions, and surely since such anticipatable and handleable scenarios can occur in runtime exceptions as well as checked exeptions - would it not make sense to treat them the same.
Should one do this through listing runtime exceptions in the throws clause - and hope? Does rethrowing it as a user defined checked exception help in this respect (by forcing through the compiler a client to handle it)?
Edit:
(for instance where one might encounter a NumberFormatException when reading files that may be supplied)

RuntimeExceptions are basically logical errors. And logical errors should be corrected in code instead of throwing them across your code base.
Exceptions are scenarios which occur rarely but when do, the flow of program changes drastically.
You CAN wrap a RuntimeException into a checked exception but That's NOT recommended. A logical error in your method is not supposed to be handled outside your method and more bad if you providing your method to be used as an API to other developers.
To add one more point, If you are developing a framework it seems logical to throw the RuntimeException so that developers can handle it by correcting their code but if you are developing a library, be far far away from doing that.
To know difference between framework and library see this: What is the difference between a framework and a library?

Related

Event which triggers if an Exception was thrown

Is it possible to create something like an event in java which will be triggered if an Exception was thrown?
I want to make something like a exception tracking system which sends all Exception to a central server.
Is this possible or do I have to call a method on myself within every catch block?
The recommended way to handle this would be with logging (for example SLF4J and Logback). You can configure loggers to send the messages to a centralized logging server, but you still need to manually log the exception and if applicable, handle it.
If you were hoping for an automagical way to just forget about exceptions, that's not really possible. Exception handling is not as easy as it may seem, if you intend to make your applications robust and easily debuggable.
A good additional "trick" is to use Thread.setDefaultUncaughtExceptionHandler() to provide a final fail-safe. Its only job should be to log any exceptions that aren't handled elsewhere. However it should happen only in case there's a massive failure and the stacktrace might otherwise be lost. If it's being invoked just because some input was of the wrong format, your design and code is of poor quality.

Pattern to let client selectively handle errors in Java

I am writing a wrapper around the DefaultHttpClient to handle some of the error-prone configuration options.
For example I will pre-configure everything to handle UTF-8 properly and to shutdown the connection cleanly.
When a non-200 is returned, I thought about the client registering a handler for a specific status code and then calling it.
I would provide some default handlers to take care of simple cases.
Is this a good pattern for a clean API? If I throw exceptions, the client has to handle cases which might not happen at all as I would have to throw an exception per possible HTTP status code (or most).
The thing I like about handlers is that I can provide a couple of 'default handlers' which might be overwritten...
I'd like to hear your input and maybe get some more creative ideas.
Cheers
Currently, accepted practice for Java APIs is to employ unchecked exceptions, so client won't need to change it's internal code just to accommodate API's exceptions into client's codebase.
Instead, if you use unchecked exceptions, you'll save your code unchanged except the places where you really need to handle exceptions.
Here're slides about Robert Martin's "Clean code" book which talk about error handling best practices: slides.
I wouldn't create a different exception for each http error code. At most create one or two general exceptions and store the exact error code as part of the exception. That way if the client code just wants to log or ignore them it can, or it can get more details based on the error code.

Can I log an exception thrown and caught in 3rd-party (external) library?

My application uses some third-party libraries. I need to log some exceptions that occur inside lib (e.g. exceptions about read file), but these exceptions are caught in the same library.
Is there some way I can log these exceptions myself, even if they're not logged by the library?
Look at AspectJ. You can write an advice around construction (and maybe even thrwoing) of the FileNotFoundException. Be advised though, that it will log every time the the pointcut is reached. With some expertise you will be able to control it.
EDIT: Dave Newtwon pointed at at this example which shows how easy it is to do this once you get the hang of it.

Exception handling guidance in a Java EE 5 Web App

I’ve been surprised by how hard it is to find best practices for this on the web since it must be such a common problem.
App is based on Java 1.5 – JSF 1.2 with Faclets, Seam, JPA, Hibernate. Some Web Service calls. Some JMS.
I’m after general recommendations for Exception handling. There are roughly 3 approaches I’ve seen used but I’ve never been that sure which one is better. Assuming you can’t recover from an error do you:
1) Log the error when it occurs and re-throw it?
2) Log it when it occurs and throw some sort of generic exception?
3) Let it bubble up and then handle it in a generic exception handling servlet or similar.
I’ve tended to use option 2 on previous systems where the architecture has been fairly simple – an adaptor layer talking to various 3rd party systems throws and adaptor exception if it gets an error back and so on. We can display a nice clean message to the user on the screen and keep the details in a log. Here though the architecture is a lot more complex and I’m wondering how well it would work in practice. So I’m interested to know what you prefer and why.
Assuming you can’t recover from an error...
Assuming this error is not a functional error, I log the error and wrap the exception in an (custom) unchecked exception and let the framework/container handle it (so option 2).
I like to do it his way because:
I like to use container managed transactions and I want the container to do its job (i.e. rollback any transaction) so throwing a runtime exception is the way to go.
It minimize the exception handling work.
It make the reporting to the user easy to handle in a generic way.
If it's a functional error (i.e. an alternative flow in a use case), I log the error and wrap the exception in a (custom) checked exception because I want the caller to handle it specifically as the problem is part of the use case.
In both case, I use a root exception for each hierarchy, namely TechnicalException and FunctionalException.

How do you know there may be an exception?

Do I have to take a look at the java api everytime I instantiate an object / call a method from a class in it? Also, do I always have to know which classes are in the java api and which are not?
If the exception is checked, then the java compiler will force your invoking method to either catch the exception or declare that it could throw the exception.
If the exception that is thrown inherits from Error or RuntimeException - I.e. is unchecked, then you have no way of knowing besides javadoc and looking at the code.
A good example of the latter, is NumberFormatException, thrown by Double.parseDouble(String). The only way to know is that the javadoc tells you it could throw this exception.
Modern IDEs (Eclipse, Netbeans, IntelliJ etc) provide easy access to this documentation.
I use Eclipse IDE which will make sure you account for all thrown exceptions. I highly recommend it.
http://www.eclipse.org
Knowing what exceptions a function throw is not different from knowing what arguments it needs, and what type it returns.
You either know it, look it up, or use an IDE that does this for you. BTW for checked exceptions you will get a compile-time error, so that can also be an option.
For you second question, In general...
Packages that start with "java." or "javax." are in the J2SE API.
Most packages starting with a internet domain prefix like "com." or "org." are supplied by third parties. Don't count on com.sun being stable though.
Packages with none of prefixes the above are likely not following the package naming guidelines or predate them.

Categories

Resources