In Java, is it possible to force all exceptions to return a generic message?
(that is, uncaught exceptions.)
Context: When testing applications, I often encounter applications which leak information through exceptions. I would like to recommend a way to force exceptions to give a generic message.
Example: Give bad input to application. Application dies, giving error message from exception.
The most generic way is:
try { ... } catch (Throwable t) { ... };
Sometimes I use this method when there is an exception generated and I don't know where it comes from.
Related
I’m consuming an external SOAP service in my Spring app. The SOAP service can throw an Exception while connecting so I catch that in a try catch block:
try {
response = soapService.callService(request);
} catch (Exception e){
throw SoapServiceException("explaining",e);
}
if (BAD_STATUS_CODE.equals(response.getStatusCode()) {
throw CustomException("explaining", e);
}
return response;
As you can notice, I also want to throw an exception when response is not what caller would expect, maybe for example because valid request format but values not found in soap service.
Is this a good practice? I'm trying to prevent wrapping the response object in another object that keep the error codes. I think it would be nice if service caller handles the exceptional cases like soap exception or the response exception. Thanks for your advice.
Exception are a feature of the java programming language but are not mandatory to be used. Well you may have to catch the existing ones, but you don't have to raise new one.
This is a design decision for your application/framework/library. It is much better if the way to handle error in general is consistant accross the whole codebase. There isn't a better, universal way. It is a collective choice and also depend of the general expected behavior of your program.
A simple design
A "naive" or at least simple implementation typically would raise exception for many unsupported cases as this is an easy way to interrupt the execution, get a log of the error and an easy way to investigate.
In that way of seeing things, it isn't necessarily worth to have checked exception. Your exceptions can derive from RuntimeException, you don't need to declare them and simply raise them when there an issue.
The drawback of such design is that developpers will likely raise exception in many cases and that most these "exceptional" cases are actually common case in your application. A file is not found ? Well that's common. The network isn't available ? That's to be expected. The service didn't return what you do expect ? That can happen more often than you think...
At least in our production where we have thing like thousand of machines and hundred thousand of TPS everything will happen.
Toward a more robust implementation
So typically you'll separate what you'll consider to be something that you expect to happen and have to deal with (like a timeout for a network request or the DB being temporarilly unvalaible) or what shall never happen (a file part of your artifact distribution missing) or invalid parameters provided to a function (a code bug).
You'll keep exception for what is truely exceptionnal, and typically make them RuntimeException/unchecked because there nothing to be done. You just want such bugs to be logged and repported.
For all the rest, there may be exception in the middle but not globally. You want to deal with them and consider them as normal behavior.
In that case, the choice is your depending of the design.
But typically if I have to act and proceed normally when that occurs, I prefer as well to not have an exception. Typically for a network request, I would consider the Time Out to be actually be a valid response and returned as this to be part of the values I model in my business domain.
To have the Error and errors code part of my data domain allow me to accumulate/aggregate errors and to fine tune how I react to them. An exception on the opposite is more an all or nothing.
This allows for more flexibility on how functionnally I choose to react... Like I performed 10 requests, one time out, on returned an error, I don't want exceptions. I want the results and a "merge" strategy that depend of the functional aspects of my application.
In your example of BadStatus, I would consider it as an exception if that 's an error code I get because I provided invalid inputs (a bug in my code). But if that's because there no network or because there was an external failure, that expected behavior for me, so I would not throw.
That's my design choice, that's the teams I have been working with design choice. This doesn't has to be the universal choice. Just be sure you all agree on how to deal with such case and it match your overall software design
Checked exceptions
They force you do deal with it, and this can be a bless or a curse depending of the context.
This is a choice that you have in your design.
Do you only throw exception in exceptional cases that should not happen and use it as bug detection mechanism ? Then I think they are useless and when I use this strategy I wrap them in a derivate of RuntimeException to simplify my code and in a few key areas of my code I have generic catch all mechanisms that can be seen as framework lvl so I ensure I always return a proper response (even if that one with an error) and then I can centralize the loggging.
But again if you think the client shall alway deal with it, use the checked exception. The problem with that is that most often the caller cannot do anything directly, he may need to wrap into many intermediate just to forward it or have an handless list of checked exceptions.
So I am not that fond of them. But again that a design decision for you and the team.
Throwing exceptions in your code when the behaviour is unexpected is absolutely fine. Just be sure to mark your method
void testMethod() throws CustomException, CustomException2, ..
so that the caller of the method knows that there is a chance that an exception can be thrown.
Uncaught exceptions will cause your program to terminate so be sure to catch, and handle appropriately.
[HttpDelete]
[Route("api/employee/delete")]
public void Delete(int Id)
{
using (EmployeeDBEntities db = new EmployeeDBEntities())
{
try
{
Employee emp = db.Employees.FirstOrDefault(e => e.EmpId == Id);
db.Employees.Remove(emp);
db.SaveChanges();
}
catch (Exception ex)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(ex.Message)
});
}
}
}
In all projects that I've been working we used exactlly as you, we throw an exception instead of wrapp this in any response object. Looks good for me.
What is the purpose of writing custom exception classes when mostly what it does is same.
For eg, NullPointerException:
class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
public NullPointerException() {
super();
}
public NullPointerException(String s) {
super(s);
}
}
This is the basic template for most exception classes that I have seen and created.
One purpose I can think of is in handling these exception.But then cant this be based on Exception Message?. Mostly we write single handling code for each exception type. I know there are 'exceptions' to this.
But is there anything more to it? Isnt this repeating yourself where only the class name changes?
Also are there any JDK Exception classes that has some code than this?
I can think of several reasons:
Having multiple exception classes allows the programmer to be specific in their catch clauses, and only catch the exceptions they care about and know what to do with.
An exception class can carry information about the error that's caused the exception. For example, ArrayIndexOutOfBoundsException carries the offending array index, and SQL exceptions tends to carry database-specific error codes and messages.
Exception specifications -- that list exception classes -- can be used to check correctness at compile time.
Well, simply put, if you do not need special exception class, you should not make one. If you do, then you make one. There's no magic to it really.
If you're making a library, then you should of course think from the point of view of the developers using the library (even if it is just you): does your library throw exceptions for specific reasons and could the library user possibly want to catch specifically these, because they can realistically do something about it (just logging isn't reason enough, IMO).
Example with standard exception classes: Caller of a method might want to convert IndexOutOfBoundsException to null return value, while letting other exceptions to propagate normally.
If you want your custom exception to be handled in default ways, you extend right existing exception class, such as IOException. You can then catch your specific IO exception when you want to do something specific just there, but also let it be handled like any other IOException when you don't need special handling (can't do anything useful to recover).
If you have a totally custom exception which should never be caught by a superclass catch, which always should have specific catch block, then you extend Exception directly.
I think it's pretty rare to need to extend RuntimeException, because if it an exception meant to be caught it should be Exception subclass, and if it's meant to end the program or just generate log output, then it should be covered by default RuntimeException implementations with custom message string.
You need to have your client code know what exact exception happens by which part of code. so you need to let exception semantic and distinguished from other code block.
How to do this:
Define new exception class, so the class name tells what happens
Define a unifed/generic exception class which wraps code, message or other info. the code can tells what happens.
To summarize it, Do something let your exception have some meaning/semantics, and let its client know what exactly happens.
We will have a freedom to add few more methods into our Exception class which helps the client like rootCauseOfException(),description(),solution(),suggestions() etc.
Can refer below link:
https://stackoverflow.com/a/22698673
If your project has interdependent modules then you can maintain exception hierarchy also in the same dependency hierarchy so that if you catch single Exception in base layer then all the interdependent modules exceptions will be caught.
You can also mask some sensitive data like ip ,port etc before sending to client side. If custom exceptions are not used then some sensitive data can may get leaked to slient.
You can provide your own exception message which can be easily understandable by client rather than java's exception message sometimes which may be hard to understand .
It is basically to Handle different Exception in different ways. Say, you might want to do some different operation on ArrayIndexOutOfBoundsException than a NumberFormatException.
or more clearly
}catch (ArrayIndexOutOfBoundsException ex){
//operation 1
}catch (NumberFormatException ex){
//operation 2
}
The main purpose would be identify the custom / app-specific errors. You can also provide some additional methods there. For eg, we have custom exceptions that return custom messages, and also extracts cause and location from the stack trace.
I am going through a Spring book to learn Spring. Having gone through sections about the JDBCTemplate i was surprised to find that Spring handles most of the SQLException exceptions differently.
For example, all checked exceptions are converted to unchecked exceptions. What exactly is the benefit of this?
In my experience, the majority of SQL exceptions should be handled. For example, we have an application that talks to an Oracle PL/SQL procedure. The call to the PL/SQL procedure can return an ORA-01403: no data found exception. This kind of exception is one that you usually recover from by displaying an error message to the user. e.g. A search result did not return anything.
How would this kind of a checked exception be handled in Spring if all exceptions are unchecked i.e. Spring wont force you to handle them?
I know that you can catch RuntimeExceptions but i quite liked the idea that you are forced to handle checked exceptions. What benefit does converting some of the checked exceptions to unchecked exceptions provide?
Yes, the exceptions should be handled, but in Spring design, on higher level then the each DAO method. In fact the design where in every method there is SQLException handling is unclean copy-paste design, and when you change something, you must apply the change in every place.
There are various demands, and various places where you handle unchecked exceptions. One of these are aspects, where you can for example convert Spring's exceptions to your exceptions (uncatched exceptions need not be declared in method signature, so this convertion is very elegant). In REST method you can add generic handler that will return the error responce to the caller, and you write exception handling in only one place. In JSF/JSP based technologies you can add own error page whenever error occures.
Some people don't like checked exceptions, as they force you to do some exception management. I guess the Spring guys are of this kind.
Personally I prefer to do things as they were intended to be made:
try {
// execute some SQL
} catch (SQLException ex) {
if (ex is an expected condition) {
// deal with it: for example with a "no data found" condition
// this might mean returning null, or throwing some kind of business exception, such as
// NoEmployeeFoundException, or whatever
} else {
// this is a programming / environment error
// throw as unchecked exception
throw new RuntimeException(ex);
}
}
Of course the downside of this approach is that is more work. The upside is that you have explicitly stated in code which are the "expected" circumstances and which ones should not happen ever.
The benefit is not being forced to catch or declare them.
I'm not convinced that not finding data during user searches is exceptional, particularly at the SQL level. Turning that into a checked exception amounts to using exceptions for generalized flow control. I would consider that an anti-pattern to be avoided; YMMV.
Many SQL-related errors are code-related; IMO it's better to fail fast--during development.
What is the use of rethrowing checked and unchecked exceptions?
If you want to execute some code when a problem happens without hiding the problem.
For example, let's say you want to rollback changes if an exception occurs while writing to a database:
try {
writeToDatabase();
} catch(Exception ex) {
rollbackChanges();
}
If you use this code, the calling function will never find out that an exception occurred.
Instead, you should write
try {
writeToDatabase();
} catch(Exception ex) {
rollbackChanges();
throw ex;
}
To be somewhat blunt: to use exception handling.
Consider this, before exceptions (or, before a developer understands how to properly use exception handling) programmers would return error codes like -1 or null if something 'went wrong'. With that in mind, how would you tell something several methods back that it failed (eg: some low level IO method in a large API failed)? You could either string a lot of return nulls/ or -1's together, or just throw an exception so that it migrates back up to somewhere where it should be caught, even the JVM itself if need be as this exception might something you cannot recover from.
So basically, you would rethrow an exception if you are unable to write catch logic that can truly recover from the thrown exception. This is often the case in Java because Java forces you to catch almost all of its Exceptions since most everything is a checked exception.
As for rethrowing checked vs unchecked... Often times I will throw a new unchecked exception (RuntimeExpcetion) from inside a checked exception back up to the container when doing J2EE applications. The container has a default way of handling exceptions and showing the user a default error page. This comes from the Aspect Oriented paradigm. I also wrote about how to do this here.
At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)
I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be handling exceptions that you can reasonably recover from. If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?
More in depth discussion: Custom exceptions: When should you create them?
Reason one:
Need to catch specific stuff. If calling code needs to deal with a specific exceptional condition, you need to differentiate your Exception, and Java differentiates exceptions with different types, so you need to write your own.
Basically, if someone has to write:
catch(ExistingException e) {
if({condition}) {
{ some stuff here}
}
else {
{ different stuff here}
}
}
You probably want to write a specific extension; catch Exception matching is clearer than conditionals, IMHO.
Remember: your new Exception can be a subclass of RuntimeException
Reason two:
API consolidation. If you write an interface and you have several implementations, it's possible that they will call different APIs with a whole bunch of different non-RuntimeExceptions thrown:
interface MyInterface {
void methodA();
}
class MyImplA {
void methodA() throws SQLException { ... }
}
class MyImplB {
void methodA() throws IOException { ... }
}
Do you really want MyInterface.methodA to throw SQLException and IOException? Maybe then it makes sense to wrap the possible exceptions in a custom Exception. Which again can be a RuntimeException. Or even RuntimeException itself...
I believe that:
catch (Exception e) {
...
}
... is an antipattern that should be avoided. You might want one centralized broad catch somewhere in your application, to log an error and prevent the whole application from terminating - but having them scattered around willy-nilly is bad.
Why:
try {
if(myShape.isHidden()) {
throw new Exception();
}
// More logic
} catch (Exception e) {
MyApp.notify("Can't munge a hidden shape");
}
So you try this, and due to a coding error, myShape is null. A NullPointerException gets thrown when the runtime tries to derefence myShape. This code reports a hidden shape, when it should be reporting a null pointer.
Either make your own exception, or find a suitably specialized exception in the API. It's not as if extending Exception or RuntimeException is onerous.
When I want to treat my exceptions differently from everybody else's. If I want to catch mine and propagate everyone else's, or if I want to catch someone else's and propagate mine, or if I want to catch both but treat them differently, then I will define a separate class for my exceptions. If I want to treat them all the same, either by propagating both or by catching both (and doing the same thing either way with the caught exceptions), the I will use the standard class.
IF there is an existing Exception with the language runtime or libraries, use it ELSE create your own, document it well and that should work in 99% of the cases.
Software captures meaning.
There are almost no reasons for throwing an existing exception: the JVM already does that for you. Your version of their exception isn't really accurate and throwing "Exception" isn't meaningful, either.
You might have a DataFormatException because of a parsing algorithm you wrote. This, however, is rare.
When your program encounters an exceptional situation, it's almost always unique to your program. Why force-fit your exceptional situation into an existing exception? If it's unique to your program, then... well... it's unique. Name it that way.
Do not, however, provide a unique exception class for each unique message. One exception class can have many variant messages and supporting details.
The Python rule of thumb, translated to Java, is to define any unique exceptions at the package level. [In Python, they suggest exceptions at the "module" level, something that doesn't precisely translate to Java.]
Start always by using the common exception classes and then when a need appears to handle it specially, change it.
When creating a method first time, just let exceptions go through.
If there are exceptions that must be handled, those can either be just defined in throws or wrapped to some runtime exception or wrapped own throws exception. I prefer runtime exceptions in many cases. Defining throws definition should be avoided until there is a need for it from API point of view.
Later when a need appears to do specific handling for an exception in some caller, come back and create new exception for it.
The point is to avoid doing extra work before knowing what is needed.
I can't imagine specifically throwing a java.lang.Exception if some object/class/method had a problem. It's too generic - if you're not going to create your own Exception class, seems to me like there ought to at least be a more specific Exception-type in the API.
I would use the exceptions from the Java API when the exception relates to the API. But if an exceptional situation arises that is unique to my own API then I will create an Exception for it. For example if I have a Range object with two properties min and max and the invariant min <= max then I will create an exception InvalidRangeException.
When I am writing code this helps because I know if the exception originates because I violated one of my own conditions or its something from the Java API.
In most cases it doesn't make sense to create your own exception class.
There is a tendency in novice programmers to create their own exception class just so they can use a name that is more indicative of the type of error. So you'll find classes like FTPInitializationException, DAOFactoryException etc. even though such exceptions are not being handled differently than standard exceptions. This is clearly an anti pattern that should be avoided.