Using try-catch -- Skipping try - java

I'm trying to write a code that I can try a JSON object and if it's the wrong format inform the user somehow.
The code is :
public boolean sjekkSporingsNummer (JSONObject object){ //object is passed correct
Boolean riktigSporing = null;
riktigSporing = true; //riktig sporing is set to true
//if its true the json is correct
try {
JSONArray consignmentSet = object.getJSONArray("consignmentSet");
JSONObject object1 = consignmentSet.getJSONObject(0);
riktigSporing = true;
}catch (Exception e){ //skips straigt to here
e.printStackTrace();
riktigSporing = false;
}
return riktigSporing;
After if failes with :
07-31 12:34:07.243 15479-15479/com.example.posten E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
What seems wierd to me is that my app skips the try and goes straight to the return statement.
I would like it to try and of it failes set "riktigSporing" to false.
What am I doing wrong?

I bet it doesn't. I suspect your input parameter is null and you trigger an NPE very early.
Note also you could possibly unbox a null into a primitive boolean, and that won't work.
EDIT:
FATAL EXCEPTION: main
java.lang.NullPointerException
suggests this further. You should have a corresponding line number in your stacktrace.

Most probably you get an exception at the first line in the try block.
I think there is a better approach to code this method. Do not use boolean to show how successful was this method execution. If this method executes ok, then return nothing. But if there's an error upon execution, throw an exception specific to the error you have got.
Avoid use of general exception classes where possible. Use exception classes specific to a sitiation which caused the problem. I.e NullPointerException, JSONException, NumberFormatException and so on. If there's a custom specific possible reason or reasons for exceptions then make your custom exception class and throw it when necessary to mark the problem as precise as possible.
It will let the caller process this error properly or throw this exception further.
In general this approach makes your application more consistent and manageable.

You need to set your boolean in this catch:
catch (JSONException e) {
e.printStackTrace();
riktigSporing = false;
}
In the case of some error with JSON this catch will be called, not second one. I think in your scenario your second catch is not required.
If you want to use generally Exception, remove JSONException and let there only Exception
Note: When i looked at your snippet of code, i suggest you to use boolean as primitive data-type instead of Boolean. It will be more clear and efficient.

It is impossible. I think try block is executed without a exception thrown and thus it must go to return statement. Or else your code might not have build properly.

Related

Java know in finally that exception thrown without any variable [duplicate]

In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in another question that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
I think this is a missing C# language feature that should be added. The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be an easy task for the compiler, saving us the work of manually creating a local Exception variable and remembering to manually set its value before re-throwing an error, as well as preventing us from making the mistake of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of overwriting the main exception by throwing a new error (bad) or just ignoring the error (also bad), it could add the error as additional data to the original error.
You could always set a boolean flag in your catch(es). I don't know of any "slick" way to do it, but then I'm more of a .Net guy.
Use logging...
try {
stream.write(buffer);
} catch(IOException ex) {
if (LOG.isErrorEnabled()) { // You can use log level whatever you want
LOG.error("Something wrong: " + ex.getMessage(), ex);
}
throw ex;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not close in finally block", ex);
}
}
}
}
In vb.net, it's possible to use a "Catch...When" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:
If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.
Although a rethrow won't clear the stack trace the way "Throw Ex" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.
Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a "Try" and the Action in a "Finally".
One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.

Java Best practice when an exception in caught into java code function

I'd like to know what is the best way or best-practice to handle this kind of situation. Guess a straightforward function like this:
public Object f1() {
Object result = null;
try {
String payload = methodThrowsAnException();
result = payload;
} catch (IOException e) {
throw new IllegalStateException(e); <<<<<<<<<<<<<<<
}
return result;
}
I'd like to know if it's a good practice:
to re-throw the exception or
return a null when something has been wrong inside.
I don't know if I've explained so well.
Re-throwing caught exception is a bad idea. most often, the stacktrace will contain more or less detailed information about your architecture. This would be to useful for an attacker.
I wouldn't allow my app to get into illegal state because of the user's action. In your case, I would say:
try {
String payload = methodThrowsAnException();
result = payload;
} catch (IOException e) {
throw new IllegalArgumentException(<user's input which caused the exception>); <<<<<<<<<<<<<<<
}
There is nothing wrong with returning a null from your method if there is a particular scenario where you expect that exception.
Alternatively you can just allow the Exception to bubble up, and be handled by the caller.
When would I catch and re-throw an exception? When I can convey better meaning by throwing a new exception.
Would I include the original exception when I throw a new one? I would do it if it is a unknown/unexpected scenario which requires further debugging.
Let me share some examples:
Something unrecoverable like Out of DB Connection. I would just let the exception bubble up. It should get handled just before it reaches the user, and probably end up in a generic error message like 'Service not available. Please try again later'.
Something application related... such as backup file not found. In that case I will swallow up the FileNotFoundException and instead I will throw a BackupFileMissingException which is specific to my application. Here I don't need to include the FileNotFoundException because it is an expected scenario and there is nothing further to investigate.
I call some other API and they throw an exception, which is not documented. In this case, I will translate it into my application exception such as InterfaceApiException and include the original exception, so that it can be logged at the REST/Action layer along with the root cause.

Exception handling in this scenario

Trying my hands on Java for the first time, please be kind. I have following code in a Web Controller where a service is called based on enclosed Switch-Case statement.
Issue I am facing is, if the service call throws an Exception, this exception gets shown on the JSP page. Basically the code never reaches the lines:
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
How do I make sure the executing goes to above lines, even though an exception is thrown in the WebService call at:
statusFlag = myWebService.getMeStatus();
Should I enclose the whole Switch Statement inside try-catch block?
Snippet:
#Controller
public String mySpringController() throws Exception
{
//rest of the controller code
switch ( condition )
{
case MAY :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
case JUNE :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
case JULY :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
default:
//Do something by default.
}
return "myJspPage";
}
If that line is throwing an Exception it means that it is never returning, so statusFlag is still with its original value and the execution of that method has stopped. You need to surround it in a try - catch if you want to catch the Exception and do something about it.
I see you are using Spring. In Spring Controllers you can also have your own special methods which get invoked when an Exception occurs. Using the #ExceptionHandler annotation.
I don't see the purpose of your switch statement since each case does the same thing.
But basically you can put your webservice call in a try-catch block
try{
webservice.call();
}
catch (Exception e){
// handle the exception
}
finally{
//anything in here will be executed regardless if an exception is caught or not
}
You're writing Java in the style of C++, where you're returning error codes and then checking them to determine whether anything went wrong. There are a number of issues with this snippet, but the reason for the exception display is that you never catch the exception that's being thrown. Where you should put your try-catch block depends on what the exception means; if it's something that isn't specific to a particular month, then yes, enclose the entire switch statement to share the error handling.
As an aside, did you copy and paste your actual code, or did you try to retype an example? Those case blocks all look identical.

catch a exception with specific message

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.

When should I use an exception in java

I was trying to understand why to use exceptions.
Suppose if I have an program,
(without using try/catch)
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
System.out.println(str.length());
}
I got exception
Exception in thread "main" java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:22)
Now using try/catch,
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
npe.printStackTrace();
}
}
}
I got Exception,
java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:9)
Now my question is,
In both the cases I have got the same message printed. So what is the use of using try/catch? and
What can we do after catching exception, in this case I have printed the stack trace. Is catch used only for printing the trace or for finding exception details using getMessage() or getClass()?
The difference is pretty big, actually.
Take the first one and add a line after the print:
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
System.out.println(str.length());
System.out.println("Does this execute?");
}
}
You'll see that Does this execute? isn't printed because the exception interrupts the flow of the code and stops it when it isn't caught.
On the other hand:
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
npe.printStackTrace();
}
System.out.println("Does this execute?");
}
}
Will print both the stack trace and Does this execute?. That's because catching the exception is like saying, "We'll handle this here and continue executing."
One other remark, the catch block is where error recovery should happen, so if an error occurs but we can recover from it, we put the recovery code there.
Edit:
Here's an example of some error recovery. Let's say we have a non-existent file at C:\nonexistentfile.txt. We want to try and open it, and if we can't find it, show the user a message saying it's missing. This could be done by catching the FileNotFoundException produced here:
// Here, we declare "throws IOException" to say someone else needs to handle it
// In this particular case, IOException will only be thrown if an error occurs while reading the file
public static void printFileToConsole() throws IOException {
File nonExistent = new File("C:/nonexistentfile.txt");
Scanner scanner = null;
try {
Scanner scanner = new Scanner(nonExistent);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException ex) {
// The file wasn't found, show the user a message
// Note use of "err" instead of "out", this is the error output
System.err.println("File not found: " + nonExistent);
// Here, we could recover by creating the file, for example
} finally {
if (scanner != null) {
scanner.close();
}
}
}
So there's a few things to note here:
We catch the FileNotFoundException and use a custom error message instead of printing the stack trace. Our error message is cleaner and more user-friendly than printing a stack trace. In GUI applications, the console may not even be visible to the user, so this may be code to show an error dialog to the user instead. Just because the file didn't exist doesn't mean we have to stop executing our code.
We declare throws IOException in the method signature instead of catching it alongside the FileNotFoundException. In this particular case, the IOException will be thrown here if we fail to read the file even though it exists. For this method, we're saying that handling errors we encounter while reading the file isn't our responsibility. This is an example of how you can declare an irrecoverable error (by irrecoverable, I mean irrecoverable here, it may be recoverable somewhere further up, such as in the method that called printFileToConsole).
I accidentally introduced the finally block here, so I'll explain what it does. It guarantees that if the Scanner was opened and an error occurs while we're reading the file, the Scanner will be closed. This is important for many reasons, most notably that if you don't close it, Java will still have the lock on the file, and so you can't open the file again without exiting the application.
There are two cases when you should throw an exception:
When you detect an error caused by incorrect use of your class (i.e. a programming error) throw an instance of unchecked exception, i.e. a subclass of RuntimeException
When you detect an error that is caused by something other than a programming error (invalid data, missing network connectivity, and so on) throw an instance of Exception that does not subclass RuntimeException
You should catch exceptions of the second kind, and not of the first kind. Moreover, you should catch exceptions if your program has a course of action to correct the exceptional situation; for example, if you detect a loss of connectivity, your program could offer the user to re-connect to the network and retry the operation. In situations when your code cannot adequately deal with the exception, let it propagate to a layer that could deal with it.
try/catch will prevent your application from crashing or to be precise- the execution will not stop if an unintentional condition is met. You can wrap your "risky" code in try block and in catch block you can handle that exception. By handling, it means that do something about that condition and move on with execution.
Without try/catch the execution stopped at the error-making-line and any code after that will not be executed.
In your case, you could have printed "This was not what I expected, whatever, lets move on!"
Let's say you are connected to database but while reading the records, it throws some exception. Now in this particular case, you can close the connection in Finally block. You just avoided memory leak here.
What I meant to say is , you can perform your task even if exception is thrown by catching and handling it.
In the example you've given, you're right, there is no benefit.
You should only catch an exception if either
You can do something about it (report, add information, fix the situation), or
You have to, because a checked exception forces you to
Usual "handling" of an exception is logging the situation to a log file of your choosing, adding any relevant context-sesitive information, and letting the flow go on. Adding contextual information benefits greatly in resolving the issue. So, in your example, you could have done
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
System.err.println(
"Tried looking up str.length from internal str variable,"
+" but we got an exception with message: "
+ npe.getMessage());
npe.printStackTrace(System.err);
}
}
when looking a message like that, someone will know based on the message what went wrong and maybe even what might be done to fix it.
If you are using Exception, don't
catch(NullPointerException npe) {
npe.printStackTrace();
}
simply
catch(NullPointerException npe) {
//error handling code
}
You are menat to remove error printing. And anyways catch general exception not just specific ones.
If you look at the two exceptions, they are actually different. The first one is referring to line 22, while the second one is referring to line 9. It sounds like adding the try/catch caught the first exception, but another line of code also threw an exception.
Consequently, the exception is being thrown because you never created a new String, or set a value to the string, unless it was done in a part of the code that is not shown.
Adding a try/catch block can be very helpful with objects that you have little to no control over, so if these objects are other than expected (such as null), you can handle the issue properly.
A string is normally something that you would instantiate first, so you shouldn't normally have to worry about using a try/catch.
Hope this helps.
To answer your original question Che, "when to use an exception?"
In Java - I'm sure you've already found out... There are certain methods in Java that REQUIRE the try / catch. These methods "throw" exceptions, and are meant to. There is no way around it.
For example,
FileUtils.readFileToString(new File("myfile.txt"));
won't let you compile until you add the try/catch.
On the other hand, exceptions are very useful because of what you can get from them.
Take Java Reflection for example...
try { Class.forName("MyClass").getConstructor().newInstance(); }
catch ( ClassNotFoundException x ) { // oh it doesnt exist.. do something else with it.
So to answer your question fully -
Use Try/Catch sparingly, as it's typically "frowned on" to EXPECT errors in your application.. on the contrary, use them when your methods require them.

Categories