So we are a few guys developing this product that is communicating with a really unstable server. It often returns very strange and corrupt data. During testing we want the resulting crashes to be loud, so we discover them. But every other day we need to demonstrate our product for a potential customer. To the customer the errors will go undiscovered if we just swallow them. I am thinking about implementing something like this around all server communication to quickly switch between swallowing exceptions and crashing:
try {
apiCall();
} catch (Exception e) {
if(!SWALLOW_EXCEPTION) {
throw e;
}
}
Is this an awesome idea, or can it be done in a better way?
I would recommend using a Logger like SLF4J, java.util.logging or Log4j. Any log messages that are 'debugging' but you still want tracked you can put to the DEBUG, INFO or WARN levels based on their severities. Real errors you can save for the 'Error' level.
When you do demos to customers, set your log level to Error so they don't see everything. When you are running normally though, set it to a level to capture the logging level you need.
Swallowing exceptions is never a good practice. By using a logger, you can hide them if it is giving you too much detail. You can always get access to them if you need without recompiling.
This is not pretty. How about implementing a top level (whatever that means in your context) error handler[s] that does that?
Did you intend your code to do this?
try {
apiCall();
} catch (Exception e) {
if(!SWALLOW_EXCEPTION) {
throw e;
} else {
e.printStackTrace();
}
}
If so, if this is the only place that this API is called, it seems ok to me, as long as you realize you will need to recompile for the change to take effect. You could abuse a logging framework to get that done without a recompile like this:
if (logger.isInfoEnabled()) {
throw e;
} else {
logger.error(e.getMessage(), e);
}
But I think most people looking at such a piece of code would be very taken aback. If you want to avoid the recompile, just use a System property:
if (Boolean.getBoolean("development")) {
throw e;
} else {
e.printStackTrace();//you should really use a logging framework anyway and not this.
}
You could use an 'uncaught exception handler' instead. Check out the code at http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers/ and http://www.javapractices.com/topic/TopicAction.do?Id=229. You can also write your handler to put the exceptions into a logger.
Related
I want make log with throwable only when log-level is under debug mode.
My way is
try {
// ...
} catch (Exception e){
if(logger.isDebugEnabled()){
logger.warn("ERR Occurs", e);
} else {
logger.warn("ERR Occurs");
}
}
But it is hard to change all my code and It is difficult to see the code at a glance
Is there any alternatives?
There is a simpler one line equivalent to your own:
logger.warn("ERR Occurs", logger.isDebugEnabled() ? e : null);
You might consider packaging the ternary operator as a simple static method logEx(e) if not wanting to override the logging class.
However: hiding exceptions is a bad idea - especially when not in debug mode, so you are better off with addressing the conditions causing the exception and leaving the logging as:
logger.warn("ERR Occurs", e);
Is there a better way for catching specific Exception with a message then doing this:
try{
methodThatWillProbablyThrowASocketException();
} catch(SocketException e){
if(e.getMessage().contains("reset")){
// the connection was reset
// will ignore
} else{
throw e;
}
}
For example the HttpStatusException gives me the Method getStatusCode() where i can easily compare if the error status was 404 or 502 and the can decide what to do:
try{
methodThatWillProbablyThrowAHTTPException();
} catch(HttpStatusException e){
if(e.getStatusCode() == 404){
// not found, will not continue
}
if else(e.getStatusCode() == 502){
// server errror, try again
} else{
throw e;
}
}
Most other Exceptions dont give me prober Methods, just the Message.
So my question is, is it the right way to do it? With String compares? Or is there a better way?
Just do one thing .
Collect all types of exception that are likely to be occur for your project.
Make a separate class by extending Exception.
Override the getCause() method.
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause%28%29
public Throwable getCause()
Define codes you want for different exceptions Like null-pointer 101 ,, so on......
The use that class every where . So you have to write exception only once and you can use with as many projects.
After building the class it will be reusable for all your needs
If you getting new conditions, update this class only and all the things will be done
This is a better solution according to me...
This way you can get functionality for which you are looking. you have to make it by yourself.
Relying on code or status code is fine but relying on message could be problematic as the message can change.
You should look to refactor and define multiple exceptions or define codes for different scenarios.
Assume that this piece of code is in 20 places and always the same
try {
// do something
} catch (FirstException e) {
// log it
} catch (SecondException e) {
// log it
}
Wouldn't be better to use something like this or instanceof is not good solution?
try {
// do something
} catch(Exception e) {
logException(e);
}
void logException(Exception e) {
if (e instanceof FirstException) {
// log it
} else if (e instanceof SecondException) {
// log it differently
} else {
// do something with other exception
}
}
The only thing that I really hate about the solution is catching Exception which is definitelly not the best way... Is there any better way?
In Java 7, use catch (FirstException1 | SecondException | ...)
There may be nothing wrong with catch (Exception e)—you do want to log all exceptions, don't you? I would in fact advise catch (Throwable t) because OutOfMemoryError s and StackOverflowErrors also want to be logged.
An advice from many years of experience with logging exceptions is to log them all the same way. The exception message is enough as human-readable text, and what the developer really needs for debugging is the stack trace.
Just be careful about one thing: never catch exceptions too early: catch them at a single place for the whole application, the so-called exception barrier—it is at the level where you enter and exit a unit of work.
If checked exceptions are giving you trouble at the lower level, wrap them into RuntimeException:
try {
...
}
catch (RuntimeException e) {throw e;}
catch (Exception e) {throw new RuntimeException(e);}
Only if you know precisely and in advance that there is an exception which has business-level meaning to your application, and will not abort the current unit of work, but redirect its flow, is it appropriate to catch that exception at a lower level. In practice such exceptions are rare compared to the totality of all possible exceptions thrown by the application code.
The first approach is definitely better. Generally it is a bad practice to catch Exception because in this case you catch RuntimeExceptions too.
Former is clean and great solution if you only have to log the exceptions.
Else first approach is better.
In the book "Refactoring to Patterns" one of the common refactorings is "replace instanceof with polymorphism" - in other words whenever you use instanceof, consider if polymporphism would in fact work better. . .
Having said that, for this particular question the Spring philosophy of replacing checked exceptions with runtime exceptions springs to mind (excuse the pun).
The idea is that checked exceptions can be overused - is the exception something that could be recovered from? If yes, ok. . . if not, just let it propagate up the chain. You can do this by:
Re-throwing it. . . (but better still)
Wrap it in a RuntimeException
Create a logging Aspect:
Another thing to consider is that if you do need to log these exceptions at precisely the point they occur rather than having them propagate up the chain, and that they occur in 20 different places, then they're a cross-cutting concern. . . You could have the regular method just rethrow the exception, and then write an aspect to catch and log them. . . . again using Spring makes this easy.
At the moment I am developing a website while using the Playframework2. I am just a beginner in programming. I read some books about exceptions but now in the real world , exception handling is really strange.
To be honest I don't really care what exceptions are thrown I handle all exceptions the same way.
return badrequest(); . I only use exceptions for logging.
try{
...
}
catch(Exeption e){
//log
return badrequest();
}
But this is so much boilerplate and it's really annoying to write, because every method throws the same exceptions.
Any tips , hints or resources that you could give me?
edit:
An example would be my "global" config file. Because I need to connect to the db every time I thought i could write a singleton for this problem.
private Datastore connect() throws UnknownHostException, MongoException,
DbAuthException {
Mongo m = new Mongo(dbUrl, dbPort);
Datastore ds = new Morphia().createDatastore(m, dbName);
boolean con = ds.getDB().authenticate(username, password.toCharArray());
if (!con)
throw new DbAuthException();
return ds;
}
This also results in a try and catch every time I want to connect to the db. My problem is I don't think I can handle them diffidently.
A code example :
public static Result addComment(String title) {
try {
Datastore ds = DatabaseConnect.getInstance().getDatastore();
Form<Comment> filledForm = commentForm.bindFromRequest();
Comment userComment = filledForm.get();
userComment.setUsername(Util.getUsernameFromSession(ctx()));
User.increasePointsBy(ctx(), 1);
UserGuides.addComment(title, userComment);
} catch (Exception e) {
return badRequest();
}
return redirect(routes.Guides.blank());
}
In this case I was to lazy to write the same try and catch over and over again, and this is duplicated code.
Maybe there is a book that explains how to design a big application with exception handling?
When you invoke a method, you do not necessarily have to catch the exceptions right there. You can let your callers handle them (declaring a throws clause if it is a checked exception). In fact, the ability to pass them on to the callers without any additional work is the distinguishing feature of exceptions.
My team has adopted the following coding standard: We throw checked exceptions for those rare cases when we want to recover from a failure, and unchecked exceptions for anything else. There is only a single catch block for the unchecked exceptions in a method so high in the call stack that all requests pass through it (for instance in a ServletFilter). This catch block logs the exception, and forwards the user to the "Sorry, this shouldn't have happened" page.
Have you looked at your code to examine why you're throwing all these exceptions? Exceptions are there for a reason- to tell you that something went wrong. If you're writing too much "boilerplate" try-catch code and you're not in a thousand line application, you have to refactor.
try-catch can be irritating when you have a complex block and can become very monotonous and boilerplate (Marc Gravell even said he usually uses try-finally) but as a new programmer, it would be helpful for you to examine the code that you write and figure out how to either handle or avoid those exceptions.
As akf mentions, ignoring exceptions can also be hazardous to debugging. It will be harder to track down where something catastrophic went wrong if you're missing exceptions leading up to it.
ok, im working in a j2ee project that has 2 branches in the repo and i'm ordered to mix them.
i was coding and then netbeans ask me "unreported exception blah bla bla must be caugth or declared to be thrown" and gives me the choice of just handle each exception or just throw it hoping someone else catches.
The classes i'm working with are these:
DataBase - DataObject - PersonDB(I'm working here)
DataBase an abstraction of the DBMS(supports a couple of them)
DataObject is just the CRUD, type conversion between the DBMS and java , and some reflection things for generality, it uses Database as a member variable
PersonDB is a map of the fields in the table called person to java types, this class extends DataObject
Now in the version 1(just the name actually worked in parallel) catch all the exceptions where they are produced for example in the class DataBase:
try {
Class.forName(this.driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
or in the DataObject class catching:
SQLException, NoSuchFieldException, IllegalArgumentException
now on version 2 all that is left to the up caller like this:
public BD (String Adriver, String Ahost, String Abase, String Alogin, String Apassword)
throws java.lang.ClassNotFoundException { ... }
which is the best way to go in your oppinion in this kind of issues, specially if i'm using struts
I apologize for my English
Well the first question I have to ask is: if this is a J2EE application, what are you doing manually loading JDBC drivers? This is what data sources are for.
Secondly, if you do need to dot his then ask yourself this: what is the result of this exception happening? Is it recoverable? Or is the failure so catastrophic your application can't run?
If it's so catastrophic your application can't run do this:
try {
...
} catch (SomeCheckedException e) {
throw new RuntimeException(e);
}
There is no point polluting your interfaces with "throws ..." clauses.
Alternatively if it is recoverable or potentially recoverable then you do need to handle it more nicely. It's hard to give an answer as to how though. Really it depends on the circumstances.
For example, if you're loading modules/plugins this way, you just log that plugin XYZ could not be loaded (logging the exception) and move on. If this is the direct result of a user action you need to somehow report to the user that the action failed (and also log the error), etc.
Exception handling is always a question of "Can i handle it?" - where handle means more than log and rethrow.
Sometimes it is worth to catch just to throw an exception of an other abstraction level ("Can i produce a more clear error for the caller?").
In both cases you have to think about passing the cause or not ("Has it useful informaton for the caller?") - not just do it any time, you will get tons of useless log files. When catching an exception, you would normally log the catched exception, maybe with debug level only, but in case of debugging a customers system, good log information is often the only chance to "debug" the system.
Exception handling and logging is often not done well. But for a product or longtime project it would be a good investment.