I need to do something like this:
while(prot.getProcessedTranscriptPositionFromAA(start) == null) start++;
But because prot throws NullPointerException I cannot loop like this. How can I create a loop that catches the NullPointerException, increments start, and executes getProcessedTranscriptPositionFromAA again ,and so on, until getProcessedTranscriptPositionFromAA will not throw NullPointerException ("it's ok" that the loop have the possibility to be infinite).
I never used goto and I don't even know how to use is, but will something like this will work somehow?:
*here*
try{
prot.getProcessedTranscriptPositionFromAA(start);
}
catch (NullPointerException e){
start++;
goto *here*
}
You don't need goto - there is no implemented goto in Java anyway. You can just put the try/catch in the loop. The loop can continue when the exception is caught, one thing has nothing to do with the other.
int start = 0;
boolean isNotNull = false;
while (!isNotNull) {
try {
prot.getProcessedTranscriptPositionFromAA(start);
isNotNull = true;
}
catch (NullPointerException e) {
start++;
}
}
I have written this with the assumption that you have no say over how getProcessedTranscriptPositionFromAA() is implemented. However, if you do control this method, or know the person who does, make sure it does not throw a NullPointerException when passed an index to an empty location - that is not good API design. It should instead return something that indicates that the location is empty. There is a lot of lively disagreement over whether that something should be a null or a non-null object indicating emptiness; but either way, don't throw an exception.
You should prevent NullPointerException from being thrown in the first place. A NullPointerException usually indicates there's a bug in your code.
while (prot != null && prot.getProcessedTranscriptPositionFromAA(start) == null) start++;
If getProcessedTranscriptPositionFromAA itself may throw a NullPointerException, you should fix that method too.
Normally you write throws NullPointerException on same line of class name.For handling multiple NullPointerException in single class.
You could build a wrapper Method which catches the NPE for you.
Something like:
public static boolean getSomething(ProtClass prot){
try{
//do something
return true;
}catch(NullPointerException e){
return false;
}
}
and use this function in the while expression.
Related
I am trying to follow this tutorial JUnit 5: How to assert an exception is thrown?
I use Java 10, IntelliJ 2018 and Junit 5.
I make a calculator app that adds 2 fractions. It checks whether the input has 0 in the denominator.
When I run the test The exception Message get printed out "Undefined Math Expression" but my IDE says "Expected java.lang.Throwable to be thrown, but nothing was thrown." I think there is some problem with the scope of my code? I'm a newbie, please be kind. I provided the code and the test below:
public class Calculator {
public static int[] calculate (int firstNumerator, int firstDenominator, int secondNumerator, int secondDenominator) {
String exceptionMessage = "Undefined Math Expression";
int resultNumerator;
int resultDenominator;
int[] result = new int[2];
resultNumerator = (firstNumerator * secondDenominator) +
(secondNumerator * firstDenominator);
resultDenominator = firstDenominator * secondDenominator;
try {
if (resultDenominator == 0) {
throw (new Throwable(exceptionMessage));
} else {
result[0] = resultNumerator;
result[1] = resultDenominator;
}
} catch (Throwable e) {
System.out.println(e.getMessage());
}
return result;
}
}
The test:
class CalculatorTest {
#Test
void denominatorContainsZero() {
assertThrows(Throwable.class, () -> {
Calculator.calculate(0,0,0,0);
});
}
}
The misunderstanding here appears to be in what JUnit can actually see.
JUnit isn't magical: it's just plain old Java. It can't see inside your methods to see what they are doing. All it can see is what any other code can see when it executes a method: the return value and uncaught exceptions (as well as any side effects of the method, if they are visible to the calling code).
Your method here doesn't throw an exception from the perspective of a caller: internally, it throws the exception, but it catches and handles it.
If you want JUnit to test that an exception is thrown, you need to not catch that exception.
It is never (*) the right thing to do to throw an exception and then catch and handle it yourself. What's the point? You can simply do the thing you do to handle it, without throwing the exception. Exceptions are expensive to throw, because of the need to capture the entire stack trace.
Throwable is never (*) the right exception to throw. It's the exception "equivalent" of returning Object: it conveys no type information about the exception to the caller, who then either has to do a lot of work to try to handle it; or, more realistically, should just propagate it themselves. IllegalArgumentException is the right exception to throw here, if you actually needed to throw (and not catch) an exception.
Throwable is rarely the right thing to catch. Throwable is a supertype of both Exception and Error, so you might unintentionally catch an Error, like OutOfMemoryError, which shouldn't be caught because there is nothing reasonable to do except crash your program. Catch the most specific type you can; which also means that you should throw the most specific type you can (or, at least, a type appropriate to the abstraction).
(*) This is "never" as in "ok, there are a limited number of circumstances where it may be appropriate". But unless you understand what these are, don't.
The Throwable is catched by try catch block, so Junit can not access it. Try remove the try catch block.
You are not actually throwing exception, you are catching it. For this to work, you should remove try catch block.
public int front(){
if(queue.empty()){
while(!stack.empty()){
queue.push(stack.pop());
}
}
try{
return queue.peek();
}catch(Exception e){
System.out.println("Empty");
}
// What to do here?!!!
}
I am implementing a queue using 2 stacks. Here is a function that returns the front element of the queue but is the queue is empty an exception must be raised. But there must be a return statement outside try block and I am confused and don't understand what to do
What to do here?
If throwing an exception is not an option, there's little you can do when front() is called on an empty queue: it is a programming error, so the proper course of action is to throw IllegalStateException to indicate that.
try{
return queue.peek();
}catch(Exception e){
System.out.println("Empty");
throw new IllegalStateException("Empty");
}
// return statement is no longer required here
All other options are worse from the point of view of API design: you could reserve an int value, and return it when the queue is empty, or you could change return type to Integer and return null, or you could change return type to a pair of int and boolean, with boolean indicating if the read has been successful or not. However, throwing an unchecked exception is more appropriate, because users must check if the queue is empty before asking for its front element.
I would throw an exception, something on the lines of
public int front(){
//..code
if(queue.isEmpty()) //or whatever the condition for exception is
throw new Exception(); //or whatever exception
else
return queue.peek(); //return value if exception does not occur
}
You could return an Integer type object and check in the calling code to see if the return value is null. That way if it is null, you can just assume it's empty.
Another thing you could do is have the calling code handle the exception and have the front() method throw the exception like so:
public int front() throws Exception {
if(queue.empty()){
while(!stack.empty()){
queue.push(stack.pop());
}
}
return queue.peek();
}
This means that whichever method calls front() will have to handle the exception.
You'd not do anything where your comment is but you would either return null in the catch block (making sure that your caller checks the return value for null before trying to use the result), or you could throw an exception.
As mentionend in the Subject: Java forces me to return something, because the handling of the Exception is in an own function.
public String returnLel(String mattDamon) {
try {
trick(mattDamon); // The LelException could be thrown
return "lel";
} catch (LelException e) {
handleException();
}
}
public void handleException() {
throw new RuntimeException();
}
`
Your code will not compile because the compiler is not "clever" enough to know you are throwing a RuntimeException in handleException.
In order for your code to compile you can either:
directly throw new RuntimeException(); in your catch statement (ugly)
return null after invoking handleException(); (acceptable, but still kind of ugly)
add a finally statement to finalize your method and return null or whatever if some condition has not been met (recommended)
Also note that I'm assuming LelException extends RuntimeException, otherwise your catch statement won't compile.
Well it is up to you on how you will handle the situation.
If you are able to handle the exception by say logging it and just return null as most of the comments imply that is totally o.k.
Just consider that this situation could also mean that the method "returnLel" might not be the correct place to handle this exception but to let the caller decide what to do in this situation by "throwing it further" like so:
public String returnLel(String mattDamon) throws LelException{
trick(mattDamon); // The LelException could be thrown
return "lel";
}
This means if the caller calls your returnLel-Method he will have to try/catch the Exception (or throw it further up) and could in this case mean a better design because the caller will not receive null or a String' but aStringor aLeLException` instead
Move the return statement out of the try catch.
The try block should surround the part where an exception could be thrown, what the return statement not does.
Here the java tutorials for some basic knowledge about this topic:
The try Block
The catch Block
The finally Block
I'm not familiar with java and I've been recently looking at some code written by some colleagues that's baffling me. Here's the gist of it:
public response newStuff(//random data inside) {
try {
response or = //gives it a value
log.info(or.toString());
return or;
}
catch ( Exception e) {
e.printStackTrace();
}
finally {
return null;
}
}
Is there really any point in adding a finally block here? Couldn't I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?
Is there really any point in adding a finally block here?
The answer to this is a resounding "no": putting a return statement in the finally block is a very bad idea.
I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?
It wouldn't match the original behavior, but that's a good thing, because it would fix it. Rather than returning null unconditionally the way the original code does, the code with the return inside the catch block would return null only on errors. In other words, the value returned in the try branch would be returned to the caller unless there is an exception.
Moreover, if you add return null after the catch block, you would see the correct effect of returning null on exception. I would go even further, and put a single return in the method, like this:
response or = null;
try {
or = //gives it a value
log.info(or.toString());
} catch ( Exception e) {
e.printStackTrace();
}
return or;
Actually, no. Finally is (nearly) always run, no matter what the result in the try-catch block; so this block always returns null. Here, look at this example:
public class Finally {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(finallyTester(true));
System.out.println(finallyTester(false));
}
public static String finallyTester(boolean succeed) {
try {
if(succeed) {
return "a";
} else {
throw new Exception("b");
}
} catch(Exception e) {
return "b";
} finally {
return "c";
}
}
}
It will print "c" both times.
The above mentioned exception to the rule would be if the thread itself is interrupted; e.g. by System.exit(). This is however a rare thing to happen.
The finally is always executed no matter what, and normally can be used to close sessions, etc.
Don't put returns inside a finally block.
This looks like a very bad practice. In this case your code will always return null.
The finally block is called last after the try-catch block runs. No matter if the try finished or the exception block was called. In this case, no matter which path of code is ran, you will always return null.
In the "normal" case where you put the return null after the finally there's indeed a chance to return something (either from the try or from the catch block) and if no flow yields a return object, you fall back to the return null, but you don't always return null.
I've read that a lot of people simply answer "don't use return in a finally block", without any explanation. Well, actually the code you posted is a good example where a return in a finally block is causing massive confusion. Even the, as of time of writing this, most upvoted answer, got it wrong. Your code will always execute the return null; as last command, even if there is an Exception.
But I can think of a situation where a return in a finally block actually makes sense. It appears to me that the goal of the author of your code was that the method never throws a Throwable, but returns null instead. This can actually be achieved if you modify the code like this:
public Result newStuff() {
Result res = null;
try {
res = someMethod();
log.info(res.toString());
}
catch (Exception e) {
e.printStackTrace();
}
finally {
return res;
}
}
But note that this will not call printStackTrace() on Errors and Throwables which are not Exceptions.
The "Finally" block will execute regardless of whether the "Catch" fires or not. So the behaviour is different than if you just put "return null" in the Catch block.
There should be no return statement in the finally block,remove return.
The need of finally block is where when you have such a code that should always be executed like you want to close your input stream or you want to close any connection etc.Just googled about this you will easily find the example for this.
In your case you are writing a method where you are returning something in try block and at the end you are writing finally block where you are returning null.I don't see any use of finally block here.
Finally block is used if you want to execute some statements even if code in try block or catch block generates an exception or not. But as you are using return in try block then there is no significance of putting a return in finally block. You can return directly from catch block and can remove finally block.
First understand why we need this three blocks in simple words for beginners.
1)try block: If you have doubt that your code will lead to an exception then put in try block
2)catch block: If exception arises then a piece of code you need to perform should be written in this block
3)finally block: If you want your piece of code to be executed no matters if exception arises or not then we go for finally block. Mainly this block is use for releasing resources.
For example:
try{
Connection conn=//something;
//some code for database operations
}catch(SQLException e){
e.printStackTrace()
}finally{
conn=null;
}
No matter what is result, you have to make connection as null because it is heavy object which if referenced will create load on database as only few connection objects are available.
Hence best way to keep them in finally block.
In your case, return null in finally block is bad approach as it will always return null although exception arises or not.
Should last statement be return in and non void return types method? But this is still working.
public String test()
{
try
{
// Do my work
return "myValue";
}
finally
{
System.out.println("I'm in Finally");
}
}
I'm bit lack of knowledge to understand how this work. Could someone explain me.
There is no problem with this code, because every possible path through it inevitably leads to a return statement*. It does not have to be the last statement textually, as long as it is the last statement logically (Java compiler is smart enough to figure out if it's so, and give you an error if there are paths through your code that do not return a value or throw an exception). The fact that there will be code executing after hitting the return (i.e. your finally block) does not change anything: as far as the compiler is concerned, your function has provided a return value before exiting the function.
* In fact, there is only one path through your function's code, and it terminates at the return statement.
It is sufficient in Java to make sure that all possible code paths either return a value or throw an exception. For example, the following code is valid:
public boolean test() {
if (3 < 5) {
return true;
} else {
throw new RuntimeException("Holy crap!");
}
}
In your example, your try block ends with a return, so the happy path is covered and there is no need for code beyond the finally; in addition, any exceptions thrown in the try will propagate out of the method and will have no chance to reach the end of the method, so all possible paths will never hit the section under the finally block and no return statement is needed. (In fact, a compiler may give you a warning or error about unreachable code if you added a return statement at the bottom!)
Things change when you add a catch clause, because now it's possible for code to flow beyond the try/catch/finally block:
public String test(){
try{
// Do my work
return "myValue";
}
catch (Exception ex) {
System.out.println("O noes something went wrong");
// swallow exception
}
finally {
System.out.println("I'm in Finally");
}
// Oh no! If an exception was caught, code can actually flow through here.
// Compiler will complain about a missing return statement until you add one.
// return "someOtherValue";
}
The key JLS concept for this is Normal and Abrupt Completion of Statements, combined with the behavior of try-finally.
The try block completes abruptly because of the return of "myValue". The finally block completes normally, so the whole try statement completes abruptly due to the same cause as the try block, return of "myValue".
In effect, the last statement in the method, the try statement, is one that returns a String.
In this case try and finally always execute. So, it doesn't matter where is return.
public String myfun(){
return "here";
}
or
public String myfun(){
try{
return "here";
}finally{
//will execute always
}
}
Are almost same. When, you see the flow of program. But, if there would be any conditional like
public String myfun(){
if(x==1){
return "here";
}
else{
// something here
}
}
In this case, it will raise error. Since, either any of the block will execute not both. Same as
public String fun(){
try{
return "here";
}
catch(Exception e){
//catch implementation without return
}
}