I thought that try and catch blocks stop at the statement the exception is caught, then it proceeds to the catch block. However, this is not the case and it's continuing to run the whole try block.
By the way, this is a tree with reference to 3 nodes: left, middle, and right.
The exception that is being caught is a NullPointerException where the animal name is being repeated twice. For example, 'Python' occurs at the left node, then 'Python' occurs again at the middle node.
Maybe it's because the exception is caught in another class? I'm not too sure.
So, the user input's 'AC' and the exception is caught at the organismTree.addAnimalChild()
else if (command.equalsIgnoreCase("AC")) {
try {
if(organismTree.getCursor().isPlant())
throw new Exceptions.IsPlantException();
if(organismTree.getCursor().isGetAllNodes())
throw new Exceptions.PositionNotAvailableException();
if(organismTree.getCursor().isHerbivore() && !organismTree.getCursor().isCarnivore())
throw new Exceptions.DietMismatchException();
System.out.print("What is the name of the organism?: ");
String addAnimalChild = input.nextLine();
System.out.print("Is the organism a herbivore / a carnivore / an omnivore? (H / C / O) : ");
String addAnimalChildType = input.nextLine();
while (!addAnimalChildType.equalsIgnoreCase("H") && !addAnimalChildType.equalsIgnoreCase("C") && !addAnimalChildType.equalsIgnoreCase("O")) {
System.out.println("Please print out a correct letter");
addAnimalChildType = input.nextLine();
}
if (addAnimalChildType.equalsIgnoreCase("H")) {
organismTree.addAnimalChild(addAnimalChild, true, false);
} else if (addAnimalChildType.equalsIgnoreCase("C"))
organismTree.addAnimalChild(addAnimalChild, false, true);
else
organismTree.addAnimalChild(addAnimalChild, true, true);
System.out.println("A(n) " + addAnimalChild + " has been successfully added as a prey for the " + organismTree.getCursor().getName());
}
catch(Exceptions.IsPlantException | Exceptions.PositionNotAvailableException | Exceptions.DietMismatchException e)
{
e.getMessage();
}
}
addAnimalChild() then redirects to another class.
addAnimalChild method
public void addAnimalChild(String name, boolean isHerbivore, boolean isCarnivore) throws
IllegalArgumentException, Exceptions.PositionNotAvailableException
{
try {
cursor.addPrey(new OrganismNode(name, isHerbivore, isCarnivore));
}
catch(Exceptions.DietMismatchException | Exceptions.IsPlantException e)
{
e.getMessage();
}
}
then it redirects to addPrey() in another class.
addPrey() Method
public void addPrey(OrganismNode preyNode) throws Exceptions.PositionNotAvailableException, Exceptions.IsPlantException, Exceptions.DietMismatchException
{
if (this.isGetAllNodes())
throw new Exceptions.PositionNotAvailableException();
if (this.isPlant()) {
throw new Exceptions.IsPlantException();
}
if(((this.isHerbivore() && !this.isCarnivore()) && preyNode.isCarnivore()) || ((this.isCarnivore() && !this.isHerbivore()) && preyNode.isPlant()) )
throw new Exceptions.DietMismatchException();
if(this.getLeft() == null)
{
this.setLeft(preyNode);
this.getLeft().setLeafNode(true);
if(!preyNode.isCarnivore() && !preyNode.isHerbivore() && !preyNode.isOmnivore())
this.getLeft().setPlant(true);
this.setLeafNode(false);
}
else if(this.getMiddle() == null)
{
try {
this.setMiddle(preyNode);
if (this.getMiddle().getName().equals(this.getLeft().getName())) {
this.setMiddle(null);
throw new IllegalArgumentException();
}
this.getMiddle().setLeafNode(true);
if (!preyNode.isCarnivore() && !preyNode.isHerbivore() && !preyNode.isOmnivore())
this.getMiddle().setPlant(true);
this.setLeafNode(false);
}
catch (IllegalArgumentException e) {
System.out.println("This prey already exists for this predator");
}
}
else if(this.getRight() == null)
{
try {
this.setRight(preyNode);
if (this.getLeft().getName().equals(this.getRight().getName()) || this.getMiddle().getName().equals(this.getRight().getName())) {
this.setRight(null);
throw new IllegalArgumentException();
}
this.getRight().setLeafNode(true);
if (!preyNode.isCarnivore() && !preyNode.isHerbivore() && !preyNode.isOmnivore())
this.getRight().setPlant(true);
this.setLeafNode(false);
}
catch (IllegalArgumentException e) {
System.out.println("Animal already exists");
}
}
}
It continues to print the System.out.println(), even though the exception was indeed caught.
I just thought of something, does the try block continue to run after it finishes the catch block?
It goes through the try block, catches the exception, goes through the catch block, then continues with where the try block left off at?
I can clarify more if you guys need me to.
Sorry if this is really long.
None of your code is catching NullPointerException. You are only catching other Exception classes.
Related
I made a method which purpose is to delete list of questions. The method Test contains questions, answers, number of questions, points. And works fine.
I get the following error:
Unreachable statement on : System.out.println("The test \"" + tests[indice - 1].getNomTest());
Here is the code:
public static int supprimerTest(Test[] tests, int nbrTests) {
int longueurTests = tests.length;
int indice = 0;
int noTest = 1;
int saisieNoTest = 0;
String nomTest;
System.out.println("***DELETE A TEST***\n");
if (nbrTests > 0) {
boolean fin = true;
do{
System.out.print("Please enter a number of the question to be deleted");
try {
indice = Clavier.lireInt();
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
}
}catch (Exception e) {
if (nbrTests < 1){
System.out.print("ERROR ! the number must be between 1 and " + nbrTests + "try again...");
}else {
System.out.println("ERROR ! the number must 1. ... Try again...");
}
}
}while (fin);
}else {
System.out.println("Il n'existe aucun test.");
System.out.print ("\nTPress <ENTRER> to continue ...");
Clavier.lireFinLigne();
}
return nbrTests;
}
Thank you for your help.
The reason you have that error is because exceptions act similar to a return statement where it'll get caught by the nearest Exception handler.
Since you have:
throw new IndexOutOfBoundsException();
Any code underneath that throw will never be reached because it immediately jumps to your catch block.
I hope that makes sense. :)
When you use try statement, it throws exceptions automatically if it is being detected. Therefore, simply take out the throw exception line, then your code should work.
When you throw an exception, the code below the throw will be not executed. Throw invoke exception and the method can continue only in catch/finally block. Lines after throw new IndexOutOfBoundsException(); cannot be reached. Maybe your code should be following:
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
}
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
The following code throws an exception if the list is empty and I want to getLast(). Also, I want to modify it with throw/catch-blocks, so that the message of the exception is going to appear on the console.
double foo(double[] numbers, double n) {
LinkedList<Double> list = new LinkedList<Double>();
for (double x : numbers) {
if (x > 0 && x <= n && x % 2 != 0) {
list.add(x);
}
}
Collections.sort(list);
return list.getLast();
}
My idea was:
double foo(double[] numbers, double n) {
LinkedList<Double> list = new LinkedList<Double>();
for (double x : numbers) {
if (x > 0 && x <= n && x % 2 != 0) {
list.add(x);
}
}
Collections.sort(list);
try{
return list.getLast();
} catch (Exception e){
System.out.println("caught: " + e);
}
return list.getLast();
}
Is this right? Did the exception get caught? What about the code after the throw/catch-block? Is it going to execute? If yes, is the exception going to be thrown again by return list.getLast();?
If list.getLast() throws an exception, it will be caught and the message will be printed. Then you will do the exact same thing and throw the exact same exception.
If you are relying on that exception being thrown when the list is empty, consider rethrowing the exception:
try {
return list.getLast();
} catch (Exception e) {
System.err.println("Caught: " + e);
throw e; // re-throw
}
// no "return" outside since we'll have thrown our previously caught error.
Is this right? If you want the exception to be thrown after print, it might be right functionality-wise, but calling getLast() twice is not the "right" way to do it.
Did the exception got caught? Yes, it did.
What about the code after the throw/catch-block? Is going to execute? Yes, it is going to execute. Since the exception was caught and not re-thrown, the execution continues as usual.
If yes, by return list.getLast(); is the exception going to be thrown again? Yes, the exception will be thrown again.
I think what you are looking for is:
try {
return list.getLast();
} catch (Exception e){
System.out.println("caught: " + e); // consider e.printStackTrace()
throw new RuntimeException("Failed to get last", e);
}
}
Why use try / catch at all. If all you want to do is determine if the list is empty what about checking list.size() != 0? Then return list.getLast() if true or Double.Nan and a message to the console if false.
I have the following code: my new code here
try{
int a=10, b=0;
if(a<b) {
throw new Exception("false");
}
String n = "30.0";
float ff = (float) 0.0;
if (Float.parseFloat(n) < ff) {
throw new Exception("big");
} else {
throw new Exception("add");
}
System.out.println("hai"); //unreachable code
} catch(Exception e){
e.printStackTrace(System.err);
}
Could someone please help me understand why the last statement is unreachable and how to solve this?
What's important to understand here is that when you throw an exception, the rest of the code is skipped. In this case this means that System.out.println("hai"); is always skipped, since you throw an exception in both branches of the if-statement. If it's always skipped, it's unreachable!
Here's an illustration:
try {
int a=10, b=0;
if(a<b) {
throw new Exception("false");
}
String n = "30.0";
float ff = (float) 0.0;
if (Float.parseFloat(n) < ff) {
throw new Exception("big"); ----------------------.
} else { |
throw new Exception("add"); ------------------. |
} | |
System.out.println("hai"); //unreachable code | |
} catch(Exception e){ | |
/* execution continues here */ <----------------+---'
e.printStackTrace(System.err);
}
If you want the "hai" to be reachable, you'll have to move it to a place where it's not always skipped. For instance to below the catch block:
try {
int a=10, b=0;
if(a<b) {
throw new Exception("false");
}
String n = "30.0";
float ff = (float) 0.0;
if (Float.parseFloat(n) < ff) {
throw new Exception("big");
} else {
throw new Exception("add");
}
} catch(Exception e){
e.printStackTrace(System.err);
}
System.out.println("hai"); // reachable!
You throw an exception, therefore you will never reach the print
You are throwing the Exeption, so method execution will stop there itself and return from that point.
To solve you cab use try-catch to catch the Exception.
Your code always throws one exception or the other, which is why the code following is never reached.
how to solve this issues
Don't throw an exception in one of your cases, or don't have code after code that always throws exceptions.
I'm working on a project where we are to create a cash register system that gives errors for orders of $0.00 and 0 total items. The code for the exceptions is below. I have to use this method.
public boolean ValidateOrderTotal(double total)
{
boolean validTotalFlag = true;
try
{
if (total < 0)
Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
throw invalidTotalEX;
}
catch (Exception invalidTotalEX)(
validTotalFlag = false;
SetTotal(0.00);
System.out.println(invalidTotalEX);
}
return validTotalFlag;
public boolean ValidateOrderProductTotal (double totalItems)
{
boolean validProdctTotalFlag = true;
try
{
if (totalItems < 0)
(Exception invalidProductTotalEX = new Exception ("Product total must be >=0");
throw invalidProductTotalEX;
}
}
catch (Exception invalidProductTotalEX)(
validProdctTotalFlag = false);
SettotalItems (0);
system.out.println (invalidProductTotalEX);
)
return valid ProductTotalFlag
if (total < 0)
Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
throw invalidTotalEX;
needs curly braces
if (total < 0) {
Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
throw invalidTotalEX;
}
You have a second if with the exact same issue.
Also your catch blocks need to use { and } around the statements. You are using ( and ) in some places.
As it throws error when it is 0 it should be:
if (total <= 0) {
Exception invalidTotalEX = new Exception ("Total mst be > $0.00");
throw invalidTotalEX;
}
"catch (Exception invalidTotalEX)(" -
there should be last '{' after "catch (Exception invalidTotalEX)(" instead of '('
Variable name does not matter, for example:
viktor#Viks-pro:~/tmp/test $ cat ExTest.java
import java.util.*;
public class ExTest
{ public static void main(String[] args)
{ try
{ throw new Exception("Something should be different");
}
catch(Exception e)
{ System.out.println("Exception: "+e.getMessage());
}
}
}viktor#Viks-pro:~/tmp/test $ java ExTest
Exception: Something should be different
I am trying to write a try catch block like the following, but put it inside a loop. My issue is that when i put it in a while loop, it runs x amount of times. i want it to stop when the first try is successful. but give the option to run up to 3 times.
try {
myDisplayFile();
} catch (FileNotFoundException e1) {
System.out.println("could not connect to that file..");
e1.printStackTrace();
}
public static void myDisplayFile() throws FileNotFoundException{
Scanner kin = new Scanner(System.in);
System.out.print("Enter a file name to read from:\t");
String aFile = kin.nextLine();
kin.close();
Scanner fileData = new Scanner(new File(aFile));
System.out.println("The file " + aFile + " contains the following lines:");
while (fileData.hasNext()){
String line = fileData.next();
System.out.println(line);
}//end while
fileData.close();
}
int max_number_runs = 3;
boolean success = false;
for( int num_try = 0 ; !success && num_try < max_number_runs ; num_try++ )
{
try
{
/* CODE HERE */
success = true;
}
catch( Exception e )
{
}
}
int someCounter = 0;
boolean finished = false;
while(someCounter < 3 && !finished) {
try {
//stuff that might throw exception
finished = true;
} catch (some exception) {
//some exception handling
someCounter++;
}
}
You can break; within a try catch block and it will exit the loop that it's in (not just the try catch block), but from a readability stand point, this posted code might be better.
finished = true should be the final line of the try block. It won't throw an exception. And it will only execute if every other line of the try block executed without an exception. So if you get to finished = true, you didn't throw and exception, so you can toggle your flag and exit the loop.
Otherwise, if an exception is thrown, the finished = true; line won't execute. You'll deal with the exception, then increment the someCounter++ variable.
This is ideal from a readability standpoint because all possible while loop exits are marked in the conditional part of the while loop. The loop will continue until either someCounter is too large, or finished returns true. So if I'm reading your code, all I have to do is look through your loop for the parts where these variables are modified, and I can quickly understand the loop logic, even if I don't yet understand everything the loop is doing. I don't have to hunt for break; statements.
I hope I understood your problem correctly. Here's a way.
int noOfTries = 0;
boolean doneWithMyStuff = false;
final int MAX_LOOP_VAL = 10;
int noOfLoops = 0;
while(noOfTries < 3 && noOfLoops < MAX_LOOP_VAL && !doneWithMyStuff) {
try {
// Do your stuff and check success
doneWithMyStuff = true;
}
catch (Exception e) {
noOfTries++;
e.printStackTrace();
}
finally {
// Close any open connections: file, etc.
}
noOfLoops++;
}