Handling a Java Exception - java

I can't figure out why my code isn't compiling correctly.. I can go through the code till it gets to the catch block. It works, displaying the message, so I know it's catching the error. However, it ends my program saying I have that same error at the same place. I can't see what I am doing wrong. Thanks for any help!!
class Verification {
String detAccess(String[] pL, String[] uL, String pass, String user) {
int pos = 0;
String access = "";
try {
for (int i=0; !user.equals(uL[i]); i++)
pos++;
} catch (ArrayIndexOutOfBoundsException exec) {
System.out.println("Username doesn't exist.");
throw exec;
}
if(pass.equals(pL[pos])) {
access = "MEMBER";
} else {
System.out.println("Incorrect password.");
access = "DENIED";
}
return access;
}
}

You are rethrowing the exception - throw exec;

You should rewrite your code to something like this:
int pos = -1;
...
for (int i=0;uL.length; i++)
{
if(user.equals(uL[i])) { pos=i; break; }
}
...
if(pos==-1)
{
// user not found
} else {
// test the pass with pos as index
}

You're rethrowing the exception.
Another thing:
if(pass.equals(pL[pos])) {
access = "MEMBER";
That will cause the exception to come up again even if you didn't rethrow it as it'll try to check the password list with a nonexistent index.

you are throwing the exception back up. the point of handling the exception is that it wron't carry on.

Two problems:
You're catching and rethrowing the exception; if you "handle it", you don't need to rethrow it.
You're using "Exception Handling" to manage the "normal control flow" through your program. This is generally considered "bad style". Can you not control your iteration, and determine that "you're done" by looking something else?
UPDATE: i.e. nio's example

The code is compiling correctly if you're able to run it. As for the program ending in error, that's because you're throwing an exception:
throw exec;
You successfully caught the exception, but then you threw it again. If nothing else catches it, the program will terminate in an error.

Related

Try Catch block works but test assertThrows fail (Junit 5)

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.

try-catch in for loop

I have met something that I cannot explain to myself today. It was a small task on an online resource to write a program that will be run on some tests. Can you please explain me the difference between two methods and why one of them fails on some tests (I don't have them).
The task is to write a static method that opens a connection and then tries 3 times to do some abstract stuff with this connection by calling its method. The problem is that any method you use can throw an exception (open connection and connection method). You must try to do the stuff exactly 3 times (if all attempts failed - throw an exception) and another condition is that every opened connection must be closed.
The connection class called RobotConnection and it implements AutoCloseable. This class has method void moveRobotTo(int x, int y) (it is the "do stuff method" from the task). You can get instance of RobotConnection only by calling RobotConnectionManager.getConnection(). Methods of these classes can throw RobotConnectionException extends RuntimeException.
So the real question COMES HERE:
This code fails (no idea why, presumably infinite loop):
public static void moveRobot(RobotConnectionManager robotConnectionManager, int toX, int toY) {
boolean success = false;
for (int i = 0; !success && (i < 3); ++i) {
try (RobotConnection connection = robotConnectionManager.getConnection()) {
connection.moveRobotTo(toX, toY);
success = true;
}
}
if (!success) {
throw new RobotConnectionException("3 attempts failed");
}
}
And this one was accepted as working (I cannot see the real difference =( )
public static void moveRobot(RobotConnectionManager robotConnectionManager, int toX, int toY) {
boolean success = false;
for (int i = 0; !success && (i < 3); ++i) {
try (RobotConnection connection = robotConnectionManager.getConnection()) {
connection.moveRobotTo(toX, toY);
success = true;
} catch (RobotConnectionException e) {}
}
if (!success) {
throw new RobotConnectionException("3 attempts failed");
}
}
In your first method, you don't catch RobotConnectionException. Consequently, it can fail at most once, rather than the required exactly 3 times.
The difference is that in the first case, you say "open and clean up the connection, but I don't know how to deal with exceptions: let them propagate up the call chain to something which can handle it":
try (RobotConnection connection = robotConnectionManager.getConnection()) {
// ...
}
whereas in the second case, you say "open and clean up the connection, but if an exception occurs, I will deal with it myself; the action I will take is to do nothing":
try (RobotConnection connection = robotConnectionManager.getConnection()) {
// ...
} catch (RobotConnectionException e) {}
If a RobotConnectionException is thrown in the first code snippet, then it might come from inside the try statement. Since you do not catch it, you will not necessary make three attempts.
More information on java exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/

Error handling with if statement

This is to validate my GUI input and make sure the user can not enter values out of range
I'm trying to handle this exception with if statement but I'm still printing the red error message. I just want the "Value out of range" message to be printed. I don't want those red exceptions error in my console. Please help or advise. Any other way to handle this can is fine with me.
if (totalTimeToTakeOff <= 0 || totalTimeToLand <= 0 || arrivalRate < 0
|| arrivalRate > 1 || departureRate < 0 || departureRate > 1
|| remaingFuel <= 0 || numOfRunways <= 0 || sIMULATION_TIME < 0) {
throw new IllegalArgumentException("Values out of range");
}
Well what you are doing here is creating a new IllegalArgumentException object, and then this method throws this exception. When you throw an exception, the part of your code that calls this method has to handle that exception OR those 'red lines' (the stack trace, basically) are printed. So, for a simple example, say that you have the method divide()
public double divide(double a, double b){
if(b==0){
throw new IllegalArgumentException("Divisor cannot be 0");
}
return a/b;
}
Now, when some other part of your code calls this method, you can choose to handle the IllegalArgumentException that is thrown by this method.
try{
double c = divide(a,b);
}catch(IllegalArgumentException e){
//put whatever code you want here
}
If you don't catch the exception, then your code breaks and the stack trace (the red text) is printed out. So in other words, your code is functioning as intended; that section of code throws an IllegalArgumentException under some circumstance, and the code that calls that method does not catch the exception and handle it (for example by printing out the message about the exception).
Also, just a minor note- an error in java is different from an exception. An error signifies a process from which the program cannot recover, and an error cannot be caught. Exceptions (all classes that subclass the Exception class) can be caught. An exception can either be checked or unchecked - checked exceptions MUST be caught via a catch statement, whereas unchecked exceptions don't. An example of a checked exception is the IOException, whereas an example of an unchecked exception is the IllegalArgumentException you have displayed here.
One more thing- exceptions are meant to signify an abnormality in your code. If this IllegalArgumentException was thrown from say, a class constructor or a method that can be used for many general purposes, then it makes sense to throw it. However, if that method exists solely for the purpose of checking whether input is valid, then have it return a boolean value (true or false) rather than throwing an exception.
One other reason to this is because exception handling tends to be rather slow in comparison to simply returning a true or a false.
You need to understand this please look into it.
Basic understanding is
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught.
}
There is also an finally block which will always be execute even if there is an error. it is used like this
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught & the returned.
} finally {
// This will always execute if there is an exception or no exception.
}
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
So you would need to catch exceptions like
try {
rows=scan.nextInt();
} catch (InputMismatchException e) {
// When the InputMismatchException is caught.
System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
// When the NoSuchElementException is caught.
System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
// When the IllegalStateException is caught.
System.out.println("Scanner is close");
}
You could just print to the console and exit Java (instead of throwing an exception), as that is what an Exception does in essence.
System.out.println("Values out of range");
System.exit(0);
Alternatively, catch the exception when calling the method
try{
if(checkValues())
...
}catch(Exception e){
System.out.println("Values out of range");
}
you could check the values without throwing an exception
if (!checkValues())
System.out.println("Values out of range");

Loop with repeated exception catching

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.

Learning Try-Catch

I'm a Java beginner so please bear with me
static int load = 100;
static int greet;
public void loadDeduct(int cLoad, int c){
int balance;
balance = cLoad - 7;
System.out.println("Your balance: " + balance);
}
public void loadDeduct(int tLoad){
int balance;
balance = tLoad - 1;
System.out.println("Your balance is: " + balance);
}
public static void main (String [] args){
int choice;
Scanner scan = new Scanner(System.in);
System.out.println("I'm a cellphone, what do you want to do?");
System.out.println("Press 1 to send SMS / Press 2 to Call");
choice = scan.nextInt();
CellphoneLoad N95 = new CellphoneLoad();
if (choice == 1){
N95.loadDeduct(load);
}else if (choice == 2){
N95.loadDeduct(load, greet);
}else{
System.out.println("Invalid Option!!!");
}
How do I implement the exception handling with this program?
I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. It was just an exercise we were asked to do. I want to replace the if else statements with a try-catch blocks... is that possible?
One important principle to consider with exceptions in Java is that there are two types:
1. Runtime
2. Typed/explicit (for lack of a better word)
Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error.
Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them.
In the case of the code above, there isn't really a place that feels like it should use exception handling.
And as Patrick pointed out, you don't generally want to use exceptions for flow control.
It is not ideal to use Exceptions for flow control. From your code it is not clear what Exceptions might be thrown. Maybe you can elaborate a bit more.
The Scanner.nextInt() method can throw a few exceptions. The linked page of the API Specifications lists out the three exceptions which can be thrown.
For example, if a non-integer value is entered, such as "one" instead of 1, an InputMismatchException can be thrown.
In general, a try-catch is used to catch exceptions, as illustrated in the following code:
try
{
Integer.parseInt("one"); // Statement that can cause an exception.
}
catch (NumberFormatException e) // Specify which exception to catch.
{
// Code to handle the NumberFormatException.
}
More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials. In particular, the Catching and Handling Exceptions section may be useful.
Adding exceptions in this piece of code does not add much value.
What I can think of is something like this:
public static void main (String [] args){
.....
try{
handleUserChoice(choice);//new method
}
catch(InvalidChoiceException e){
System.out.println("Invalid Option!!!");
}
}
The only part of your code that might possibly throw an exception is the call to:
scan.nextInt();
According to the JavaDocs, this can throw the following possible exceptions:
InputMismatchException (if the next
token does not match the Integer
regular expression, or is out of
range)
NoSuchElementException (if
input is exhausted)
IllegalStateException (if this
scanner is closed)
So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so:
try {
choice = scan.nextInt();
}
catch (InputMismatchException e) {
System.out.println(e.getMessage());
}
catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature.
You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime).
In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement:
switch (choice) {
case 1: N95.loadDeduct(load);
break;
case 2: N95.loadDeduct(load, greet);
break;
default: System.out.println("Invalid Option!!!");
}
I don't see any reason to use exceptions instead of the if-else block. you could try using a switch statement, it'd look better.
you should use exceptions to handle errors that might occur inside the methods loadDeduct. then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong.
It's really pretty simple. First identify where you want an exceptioon. There can be exceptinos thrown by library code or you can throw your own. Then use a try .. catch to handle it. Here's a simple "hello, world" ish example:
public class TryTry {
public void doIt() throws Exception {
System.err.println("In the doIt method.");
throw new Exception("Hello there!");
}
public static void main(String[] argv){
TryTry t = new TryTry();
// here we'll catch it.
try {
System.err.println("About to call doIt().");
t.doIt();
} catch (Exception e) { // e now has your exception object
System.err.println("In the exception handler.");
System.err.println("Exception says: "+ e);
}
}
}
The effect of throw is to construct that exception object and send it up the stack until it's caught. To catch it, you surround the code that might throw it with tr { ... }, and handle the exception with catch.
Here's the results:
javac TryTry.java && java TryTry
About to call doIt().
In the doIt method.
In the exception handler.
Exception says: java.lang.Exception: Hello there!

Categories