Java If NoSuchElementException is returned - java

How can I make an if statement to check if "NoSuchElementException" is returned from a function? Something similar to what I have below.
if (functionReturns == "NoSuchElementException")

How can I make an if statement to check if NoSuchElementException" is
returned from a function?
If you meant that your function returns a String with the value as NoSuchElementException, use equals instead of == :
if("NoSuchElementException".equals(functionReturns)) { }
If you meant that your function can throw a NoSuchElementException, use a try-catch. The catch block will be triggered when the function throws a NoSuchElementException.
try {
function();
} catch(NoSuchElementException e) {
//NoSuchElementException was thrown
}
If you meant that your function actually returns an instance of NoSuchElementException, you can use :
NoSuchElementException.class.isAssignableFrom(functionReturns)

If method is throwing exception then simple use try and catch .
like
boolean isException = false;
try{
//method that throws
}catch(NoSuchElementException e){
isException = true;
//or perform what you like
}

First of all NoSuchElementException or any other Exception is basically Thrown by a method not Returned. So you can/should not check it via return type.
The best approach to handle any type of Exception is try catch blocks. Ex:-
try {
// Probable Exception Throwing code
} catch(NoSuchElementException e) {
// handle/log specific type of error
}
catch(Exception e) {
// handle/log Generic error if none specific is defined
}
Find more about Exception in the Official Docs here

if you are using if statement then there must be thrown more than one error so in java 7
In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This is also known as multi catch.
Before Java 7 you would write something like this:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(NoSuchElementException e) {//work as if if (functionReturns == "NoSuchElementException")
logger.log(e);
} catch(NoSuchElementException1 e) {//work as if if (functionReturns == "NoSuchElementException1")
logger.log(e);
} catch(NoSuchElementException2 e) {//work as if if (functionReturns == "NoSuchElementException2")
logger.severe(e);
}
As you can see, the two exceptions NoSuchElementException1 and NoSuchElementException2 are handled in the same way, but you still have to write two individual catch blocks for them.
In Java 7 you can catch multiple exceptions using the multi catch syntax:
try {
// execute code that may throw 1 of the 3 exceptions below.
//combind way to catch multiple error
} catch(NoSuchElementException1 | NoSuchElementException2 e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
Notice how the two exception class names in the first catch block are separated by the pipe character |. The pipe character between exception class names is how you declare multiple exceptions to be caught by the same catch clause.

This way worked for me.
if(function.equals("NoSuchElementException"))

Related

Extended Exception handling

I have several custom Exception classes. (Diffrent Error Codes / Error Messages)
Some of those lead to termination. This is why i let them propagate to the main.
To print the error code + message.
If I catch the superclass, is there a way without having a long if else list to check which subclass i have cought to get to the overriden method?
Would it be more readable to have several catch statements?
Should I cast them at a lower level to a higher Exception and only catch this exception?
If you need to handle a SubclassOfException in a particular way, use catch SubclassOfException.
There's no point in using a chain of instanceof checks when this is basically what the exception handling already does.
try {
} catch (SubclassOfException e) {
// Do something specific to SubclassOfException
} catch (Exception e) {
// Do something for other types.
}
is basically the same as:
try {
} catch (Exception e) {
if (e instanceof SubclassOfException) {
// Do something specific to SubclassOfException.
// Note that you have to cast explicitly if you want to use
// subclass-specific properties of SubclassOfException.
} else {
// Do something for other types.
}
}
I think it is clear that the first is more readable, and it will be more efficiently executed, since this is how the JVM expects exception handling code to be written.
Another advantage of writing in the first way is that you can't write:
try {
// ...
} catch (SubclassOfException e) {
} catch (SubclassOfSubclassOfException e) {
}
because the first catch would catch all exceptions to be matched by the second catch, making the second catch redundant. As such, this is a compile-time error, described in JLS Sec 11.2.3:
It is a compile-time error if a catch clause can catch an exception class E1 and a preceding catch clause of the immediately enclosing try statement can catch E1 or a superclass of E1.
You need to catch the most-specific types first, and the least-specific types after.
On the other hand,
if (e instanceof SubclassOfException) {
} else if (e instanceof SubclassOfSubclassOfException) {
}
isn't a compile-time error, even though the second branch cannot be executed either; you'd just see all SubclassOfSubclassOfExceptions being handled as if they were mere SubclassOfExceptions.

In Java catch block, how do you know which method/line throws the exception?

In try block, I want to execute two functions. If the first one failed then don't execute the second. I also want to print out which function failed.
See following code.
try {
a = func1();
b = func2(); //won't execute if a failed
}
catch (Exception e) {
//TODO: print a or b failed?
}
Does the language support this scenario naturally?
If not, is the following a good practice? (I cannot think of anything wrong about it. But it concerns me as I don't remember seeing any one using return in catch.)
try {
a = func1();
}
catch {
//print: a failed
return; //if a failed then skip the execution of b
}
try {
b = func2();
}
catch {
//print: b failed
}
EDIT:
Summary of comments:
throw different exception from two methods.
In this case the methods are written by others and I have no control.
e.printStackTrace() will print line number and function
I want to do more than just printing. More like, if a failed, execute the following code.
What you want is String methodName = e.getStackTrace()[0].getMethodName());
But this is hardly a good practice. The standard way is to log the exception using appropriate method in your logging framework or (if writing a console app, which is rarely the case with Java) to print it to the error or standard output or optionally to other PrintStream, for example using printStackTrace(printStream).
But in most cases you want to propagate exception to the upper layers and handle (or decide to not handle it) by the appropriate high level code. Catching exceptions like this leads to nasty bugs. Returning from catch black is also a very bad idea in 99% of cases because exception signalizes abnormal termination of the method while returning a value does not.
As dev-null wrote e.getStackTrace() can help. But note that the exception may not be thrown by func1 or func2 themselves but by some other method they call. So you need to go through all elements of the array until you hit func1 or func2.
Calling them in separate try blocks is definitely practiced but it can get cumbersome.
Logging the stack trace if an exception is thrown will inform you which line threw the exception. If the first line in the try/catch throws the exception, the next line will not be executed.
This will work:
String failedFunc = "func1";
try {
a = func1();
failedFunc = "func2";
b = func2(); //won't execute if func1() failed
} catch (Exception e) {
System.out.println("Func '" + failedFunc + "' failed: " + e);
}
Or course, if all you're doing is printing the error, then printing the stack trace will show you exactly where it failed. The above code is however useful if you need the value of failedFunc without a full stack trace.
As I said in the comments, you can use e.printStackTrace() to determine the cause of the Exception. Since you expressed a desire for different behaviors then you have a few options. You could write two local functions to decorate your func1 and func2 calls with custom Exceptions. Something like,
class Func1Exception extends Exception {
public Func1Exception(Exception e) {
super(e);
}
}
class Func2Exception extends Exception {
public Func2Exception(Exception e) {
super(e);
}
}
Then you can write the local functions like
private static Object func1Decorator() throws Func1Exception {
try {
return func1();
} catch (Exception e) {
throw new Func1Exception(e);
}
}
private static Object func2Decorator() throws Func2Exception {
try {
return func2();
} catch (Exception e) {
throw new Func2Exception(e);
}
}
Then you can handle them however you wish,
try {
a = func1Decorator();
b = func2Decorator(); // this still won't execute if a failed
} catch (Func1Exception e) {
// a failed.
} catch (Func2Exception e) {
// b failed.
}
If you want func2 to run even when a fails you could use a finally block,
try {
a = func1Decorator();
} catch (Func1Exception e) {
// a failed.
} finally {
try {
b = func2Decorator(); // this will execute if a fails
} catch (Func2Exception e) {
// b failed.
}
}

Will an assertion error be caught by in a catch block for java exception?

Code:-
try {
Assert.assertEquals("1", "2");
} catch (Exception e) {
System.out.println("I am in error block");
}
If the assert statements fails, I would like to capture the error in the catch block. I am trying with the above code and its not happening.
Will the assertion error be caught by in a catch block for java exception?
You have almost answered your own question. Your catch block will not catch the AssertionError that the Assert throws if it fails, because it is an Error (or, more specifically, it extends java.lang.Error). See the docs for more information on this. Your catch block only catches Throwable objects that extend java.lang.Exception
If you really want to catch it - you need to use
catch (AssertionError e) {
...
However, as others have mentioned, this is a very unusual way to use assertions - they should usually pass and if they fail it is very unusual for you to want to carry on the program execution. That's why the failure throws an Error rather than an Exception. You can read more about (not) catching Error in this question.
If you just want a test the variable value, it is preferred to use if ( variableName == "1")
NB if you are testing unit-test helper code, like a matcher, it might make sense to catch the AssertionError.
If you want to catch both Exception and Error instances use:
...
catch (Throwable t)
{
...
}
Since both Exception and Error extend Throwable.
Well, I believe you are using JUnit for writing your tests. In that case, you should not catch your Assert.assertEquals() because they should pass for normal test execution. If it throws any exception, it means that your code is not performing as it should.
If you want to catch the errors in that way you need something like the following:
if (num == 1 || num == 2) {
throw new Exception();
}
You could create your own exception class and pass in the message you want.

Counting the Exception and Logging it in the same method [duplicate]

This question already has answers here:
Counting the number of exceptions happening in catch block
(2 answers)
Closed 9 years ago.
I am tring to count the number of exceptions happening and also log those exceptions as well. So what I did is, I created one method addException in which I am counting all the exceptions.
addException method will accepts two parameters, one is the String, and other is the boolean flag which means whether we want to terminate the program or not because of any exceptions. Meaning, if that flag is true, then I need to terminate the program whenever there are any exceptions.
So if you take a look into my below catch block, I have addException method call for counting the exceptions and below that method call I am logging the exceptions as well.
catch (ClassNotFoundException e) {
addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
LOG.error("Threw a ClassNotFoundException in " + getClass().getSimpleName(), e);
} catch (SQLException e) {
addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
//DAMN! I'm not....
LOG.error("Threw a SQLException while making connection to database in " + getClass().getSimpleName(), e);
}
/**
* A simple method that will add the count of exceptions and name of
* exception to a map
*
* #param cause
* #param flagTerminate
*/
private static void addException(String cause, boolean flagTerminate) {
AtomicInteger count = exceptionMap.get(cause);
if (count == null) {
count = new AtomicInteger();
AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
if (curCount != null) {
count = curCount;
}
}
count.incrementAndGet();
if(flagTerminate) {
System.exit(1);
}
}
Problem Statement:-
Now what I am looking for is-
Is there any more cleaner way of doing the same thing? Meaning right now I am counting the exceptions in a method and then printing out the exceptions in the next line inside the catch block.
Is it possible to do the both of the things in the same addException method? And if the flag is true to terminate the program, then terminate the program with the proper logging as well.
What could be the best way to re write addException method to do this?
Thanks for the help.
Is there any more cleaner way of doing the same thing? Meaning right
now I am counting the exceptions in a method and then printing out the
exceptions in the next line inside the catch block.
Is it possible to do the both of the things in the same addException
method? And if the flag is true to terminate the program, then
terminate the program with the proper logging as well.
Yes, instead of passing String cause to the addException method, you could pass the exception itself and the flag if you want. Or even do the complete catching inside the addException method like:
catch (ClassNotFoundException|SQLException e) {
addException(e, Read.flagTerminate);
}
or
catch (Exception e) {
addException(e, Read.flagTerminate);
}
or even:
catch (ClassNotFoundException e) {
addException(e, Read.flagTerminate, "Threw a ClassNotFoundException in "); //An the addException method logs the message passed.
} catch (SQLException e) {
addException(e, Read.flagTerminate, "Threw a SQLException while making connection to database in ");
}
You could have a map in the class that have stored which exceptions should stop execution and which shouldn't, with that you will only need an addException(Exception e) method.
You could even create a properties file that have a localized message for each type of exception and log that message by default.
You can also check the link suggested by #perception:
Counting the number of exceptions happening in catch block

Exception thrown inside catch block - will it be caught again?

This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?
try {
// Do something
} catch(IOException e) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}
I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.
No, since the new throw is not in the try block directly.
No. It's very easy to check.
public class Catch {
public static void main(String[] args) {
try {
throw new java.io.IOException();
} catch (java.io.IOException exc) {
System.err.println("In catch IOException: "+exc.getClass());
throw new RuntimeException();
} catch (Exception exc) {
System.err.println("In catch Exception: "+exc.getClass());
} finally {
System.err.println("In finally");
}
}
}
Should print:
In catch IOException: class java.io.IOException
In finally
Exception in thread "main" java.lang.RuntimeException
at Catch.main(Catch.java:8)
Technically that could have been a compiler bug, implementation dependent, unspecified behaviour, or something. However, the JLS is pretty well nailed down and the compilers are good enough for this sort of simple thing (generics corner case may be a different matter).
Also note, if you swap around the two catch blocks, it wont compile. The second catch would be completely unreachable.
Note the finally block always runs even if a catch block is executed (other than silly cases, such as infinite loops, attaching through the tools interface and killing the thread, rewriting bytecode, etc.).
The Java Language Specification says in section 14.19.1:
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
If the run-time type of V is assignable to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
Reference:
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134
In other words, the first enclosing catch that can handle the exception does, and if an exception is thrown out of that catch, that's not in the scope of any other catch for the original try, so they will not try to handle it.
One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost. That can be confusing the first time you see it.
If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:
public void doStuff() throws MyException {
try {
//Stuff
} catch(StuffException e) {
throw new MyException();
}
}
And now your compiler will not yell at you :)
No -- As Chris Jester-Young said, it will be thrown up to the next try-catch in the hierarchy.
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
It won't be caught by the second catch block. Each Exception is caught only when inside a try block. You can nest tries though (not that it's a good idea generally):
try {
doSomething();
} catch (IOException) {
try {
doSomething();
} catch (IOException e) {
throw new ApplicationException("Failed twice at doSomething" +
e.toString());
}
} catch (Exception e) {
}
No, since the catches all refer to the same try block, so throwing from within a catch block would be caught by an enclosing try block (probably in the method that called this one)
Old post but "e" variable must be unique:
try {
// Do something
} catch(IOException ioE) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}

Categories

Resources