Why do we have to use in catch, Exception if this class includes errors (like java virtual machine exception) or exceptions like NullPointerException...these exceptions are unchecked exception. I found examples on internet, but I don't understand why it is necessary to use Exception in this code. Why we don't catch exception that are bound to hibernate framework?
try{
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.eq("pk.stud.id",idStude));
carte = (List<StudentC>) criteria.list();
}catch(Exception e){
System.out.println("\n"+e.toString()+" "+e.getMessage()+"\n");
}
System.out.println("\nENTER UnivDAO \n");
Your hibernate code is accessing database and can update/delete/lock records.
If your code will throw unchecked exception without catch the database connection can remain open and may cause a connection leak or even lock database record(s).
Also you may have a catch in high level function that will may handle such exception the wrong way, e.g. expect some different parameter is null
The point is that such code can probably throw a whole set of different checked exception types.
And instead of asking you to catch these 5 different exceptions the authors of that API decided to reduce the operation to say "throws Exception". That reduces effort on both sides - the throws list is easier to manage now. But the downside is that you lose a bit of information on what is really going on.
This is a common practice. Sometimes it is a good idea, sometimes not.
It's not neccessary to catch any exceptions around that code. A lot of the examples catch exceptions just to demonstrate which exceptions are thrown. That example probably leaves carte set to null, or an empty list, after the try/catch block which will only cause further exceptions to be thrown, or invalid results to be returned. Instead, the exception should be thrown, and handled at a higher level, probably at the request level.
If the query results are unavailable, then it doesn't really matter whether it's because of the database being down, or a programming error. The response is usually the same. An error message is sent to the user, or default values are used. The error is logged, and you move on to the next request.
Also in the example, calling System.out or e.getMessage() means we lose a lot of information about where or when the exception occurred. It's not meant to be used in real code, instead the exception should be sent to a logger.
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.
I have quite a lot of experience with java (math, UIs and graphics mostly), but I've never seriously worked with APIs like JDBC or org.w3c.dom where you are heavily relied on handling checked runtime exceptions. So if I write a bunch of methods woriking with those kind of APIs, how do I decide what should I do with exceptions, whether I should catch them right away or add them to method's signature and thus propatate exceptions to a higher level of the frame stack, where they all are handled? It seems that all I would ever want to do with those checked exceptions is to exit the application with an error whenever one is encountered.
Generally, exceptions fall into two buckets: 1) the type you can recover from in some meaningful way. 2) the type that indicates failure and possibly a need to communicate that (logging, return some error page, display a dialog, etc.).
The former you handle close to where the exception happens (e.g. retry an http REST call), the latter you preferably handle in one place instead of littering your code with catch blocks.
Validation related exceptions in web applications are a good example of the type that you don't handle and instead you let the web application trap them and then map them to a status 400 response code.
Another example: Java throws a checked exception on just about anything that takes a character encoding. Generally you just want to pass in "utf-8" and unless you mistype that, that exception will never happen. If it does happen, it means UTF-8 is apparently no longer supported. I don't see how you could recover from that in a meaningful way. I tend to catch and rethrow these as unchecked exceptions. They'll never happen but when they do, I want the software to fail with an exception so that it gets logged somewhere.
So, if some code you are using throws a checked exception, you need to decide if you can recover from it locally. If not, you need to decide if somebody up the call stack should want/need to know about or handle the exception. If so, add it to your throws and move the decision up the callstack. If not, rethrow it as an unchecked exception and handle it somewhere centrally (e.g. log it).
This question is a bit difficult to answer.
Lets say, you are going to the market to buy something, but you don't have cash in your valet. What you have is an ATM card of some bank, but again you are not sure of whether there is enough money in your account to do the shopping.
Now, there are two things you can do here. Either,
1) You first make sure that you do have sufficient money in your account before leaving to the Market, OR
2) Reach out to the market and then see, if you can buy any items.
Likewise, In java there are two types of Exceptions
Checked Exception which is a sub-class of java.lang.Exception, and
Unchecked Exception which is a sub-class of java.lang.RuntimeException.
Checked Exceptions can be thought of synonymous to the first case of you going to shopping. Here after finding that you don't have enough balance to do the shopping, either you can decide to borrow it from someone OR do nothing, that is, quit the plan of shopping for now.
Similarly, Unchecked Exception can be thought of as you going to the market without knowing about the balance in your account. Now, at the billing counter either your transaction will be successful OR it will be declined because you don't have enough balance in your account. Here also, either you can decide to just apologize to the shop-keeper and get going OR you can call someone to bring the required money to the shop.
As you can see, what you may do in such situations is totally dependent on you.
Similarly, In programming with Java there is not much difference between the Checked and Unchecked Exception and what you want to do if Exceptions occurred is totally dependent on your personal/organizations policies.
The Java compiler only mandates this that in case of a method throwing Checked Exception, your code using that method must have to catch the Exception OR throw it one level up. While in case of Unchecked Exceptions, this is optional.
Take for Example the following method which throws a Checked Exception :
// Here compiler makes sure that you either catch exception OR declare it to be thrown
public void storeDataFromUrl(String url){
try {
String data = readDataFromUrl(url);
} catch (BadUrlException e) {
e.printStackTrace();
}
}
// Here BadUrlException is a subclass of Exception
public String readDataFromUrl(String url) throws BadUrlException{
if(isUrlBad(url)){
throw new BadUrlException("Bad URL: " + url);
}
String data = null;
//read lots of data over HTTP and return it as a String instance.
return data;
}
Now your storDataFromUrl() method can either catch the BadUrlException OR it can declare it to b throw, in which case the code using the storeDataFromUrl() method will have to do the same thing. That is, either catch the exception or throw it for someone higher to deal with it as they would like.
And now the same example, which throws an Unchecked exception;
// Here compiler does not force you to either catch exception OR declare it to be thrown
public void storeDataFromUrl(String url){
String data = readDataFromUrl(url);
}
// Here BadUrlException is a subclass of RuntimeException
public String readDataFromUrl(String url) { // Notice, it does not have a throws clause
if(isUrlBad(url)){
throw new BadUrlException("Bad URL: " + url);
}
String data = null;
//read lots of data over HTTP and return it as a String instance.
return data;
}
FEW POINTS Most of the Books advice you to use checked exceptions for all errors the application can recover from, and unchecked exceptions for the errors the application cannot recover from.
In reality most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions. The action / transaction that failed will be aborted but the application has to stay alive and be ready to serve the next action / transaction. The only time it is normally legal to shut down an application is during startup. For instance, if a configuration file is missing and the application cannot do anything sensible without it, then it is legal to shut down the application.
EDIT : Yo can read these two articles for more understanding on the topic : Three rules for effective exception handling and Best Practices for Exception Handling
The right spot to handle exception depends entirely on the concrete situation. If you just want to exit the application don't catch the exceptions but declare them in the throws clause.
For a server program however, this would not be a good strategy. For example, you don't want your server to crash whenever the DB is not reachable because of a short network problem.
Well,this is a difficult question.One of the five modularity criteria from B.Meyer book is Protection.This criterion says that if an error apear in a class,or a module,it should not spread in the hole system.So the error must be isolated from the other component of the system.
Therefor I think you should catch the exception on a low level in the system.
If exception indicates problem that is caused by external sources like problem with network, bad format of xml etc. (it depends on exception type). then you should catch such exception where you can do something about it - if thats GUI application, then catch it where you can show error dialog to user - and make him/her make decision. If thats on server, then log error - return it to client. If exception is due to programming bug, then on GUI application you can log it / or allow user to send it in email to user. For command line tool I would allow application to exit with exception and throw all its data to output, if thats GUI application - I would rather try to catch it and try to recover with giving hint to user that there is a problem.
You could also add global exception handler to your program that will automatically send such exceptions to your email.
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.
Is there any reason for not converting the following code
try {
// Do something
} catch (XException e) {
e.printStackTrace();
} catch (YException e) {
e.printStackTrace();
} catch (ZException e) {
e.printStackTrace();
}
to this:
try {
// Do something
} catch (Exception e) {
e.printStackTrace();
}
I know the 2nd one catches all kinds of Exceptions, and I don't mind that. And let's say I want to handle all exceptions in the same way. Is the performance difference considerable?
The Java try/catch mechanism has been so highly tuned in successive JVM's that their performance is never something you should be explicitely worried about. Rather, you should be coding those blocks according to whether you need to handle the caught error scenarios in different ways. In your example you are just printing a stack trace so it is not beneficial to catch the specific errors - but your use case will actually determine wether you should be rolling up or down for these try/catch blocks.
This separation is only because you would be able to perform different task for different exceptions. Like if you receive parse exception and you get IO exception so you would know exactly what to do with each exception.
In newer version this blocks has been minimized with multiple exception in on block which will help the coder and increase the readability. e.g.
try {
// Do something
} catch (XException | YException | ZException e) {
e.printStackTrace();
}
I wouldn't worry about performance at the moment (unless you know it's a real issue).
You may want to convert for readability (if the same action is performed for each type of excpeption), but don't forget that catching Exception will catch lots of other stuff besides XException, YException, ZException. Is there a useful base class for those, and can you catch that instead ?
Occasionally you may want to perform different actions on different exceptions.
Even if you don't you still help other programmers see the complete picture rather than hiding it in one big Exception; which also happens to catch all Runtime exceptions.
The main reason you catch the exceptions separately is you may want to do something different based on which exception has been thrown. For example when parsing a file, you may want to throw a FileNotFoundException, or an IndexOutOfBounds exception. One tells you you cannot find the file to parse, while the other tells you there was a problem during the parse itself. It's much more informative to handle these separately as they are entirely different problems. For example the end user could receive different error messages based on the exception thrown.
There is a difference in catching RunTimeExceptions like NullPointerException. Those will be caught in the second case but not in the first.
In the vast majority of situations you want exception handlers to be as specific as possible so that your code is resilient and adopts an appropriate recovery strategy in the event that an exception occurs. Taking a general approach to exception handling is unwise as the handler must react to any exception possibility which this can result in code being more error-prone when unexpected exceptions are caught which the handler was not intended to handle. In essence exception handlers with the clause catch (Exception e) is the lazy approach.
In my experience the motivation for placing an exception handler around a block of code is to catch a specific exception or set of exceptions. Therefore at the time of conception you know the exceptions you want to catch anyway, why generalise and use the Exception class?
I'd advise reading two things to gain appreciation for specific exception handling:
Effective Java Second Edition - Joshua Bloch : Chapter 9
The Java tutorial on Exceptions : Advantages of Exceptions
IMHO it is just a question of handling all errors the same way or some in a different way.
First one is useful when you want to handle different exceptions in different ways and in second case you are handling all exception in same way. Use second way when you perfectly don't know which exception will occur and if you know you can use the first one.
Not much difference from a technical perspective. The second version will catch all XYZ exceptions plus any RuntimeException that may be thrown in the try block. Check, if that is OK.
If the catch handlers all do the same for any thrown exception, then I see no problem with grouping them. Although it is not very common (in production code) to have equal catch handlers, usually they do different things or log different messages.
Reason is to handle different exceptions for ex. for a sql exception you may want to rollback the transaction but for a io exception for an unfound file u may want to create that file etc.
If we consider the performance there is no difference between handling in one catch block or with multiple.
exception can occurs for many reasons
A file that needs to be opened cannot be found (fileNotFoundException or InputStreamExcep)
A user has entered invalid data.
network connection has been lost or the JVM has run out of memory.
Types of exceptions:
Three Kinds of Exceptions are:
Checked exception:
A checked exception is an exception that a user error or a problem which is not foreseen by the programmer.
Example:if a file is to be opened, but the file is not found, an exception occurs. These exceptions cannot be ignored at the time of compilation.
Unchecked exceptions: A runtime exception is an exception that occurs that probably ignored by the programmer.It is also known as runtime exceptions.these are ignored at the time of compliation.
Errors: problems that arise beyond the control of the programmer.
Example, if a stack overflow occurs, an error will arise. These are ignored at the time of compilation.
Catching Exceptions:
Byusing try/catch, we can handle the exception.try block is placed around the code that might generate an exception.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Multiple catch Blocks:
A try block can be followed by multiple catch blocks.
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.