Cannot reach statement - java

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;

Related

Explanation of try and catch

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.

Java: how to use try/catch block with return

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.

looping over a try/catch block?

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++;
}

I get an error message as follows: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));

The index 0 is out of range

I'm getting a 'The index 0 is out of range' exception in the following try-catch block but I can't for the life of me figure out where the exception gets thrown?
try{
cs = this.con.prepareCall("{call "+storedProcName+"("+procParams+")}");
for(int j = 0; j < params.length; j++){
if (paramTypes[j].equalsIgnoreCase("Int")) {
int x = 0;
try{
x = Integer.parseInt(params[j]);
} catch(Exception e) {}
cs.setInt(j, x);
} else if (paramTypes[j].equalsIgnoreCase("Boolean")) {
boolean x = false;
try{
x = (params[j].equalsIgnoreCase("True")) || (params[j].equalsIgnoreCase("T")) || (params[j].equalsIgnoreCase("1")) || (params[j].equalsIgnoreCase("Yes")) || (params[j].equalsIgnoreCase("Y"));
} catch(Exception e) {}
cs.setBoolean(j, x);
} else if (paramTypes[j].equalsIgnoreCase("String")) {
cs.setString(j, params[j]);
}
}
}catch(Exception e){
System.out.println("---------------------------------------------");
System.out.println("Problem constructing callableStatement: "+e);
System.out.println("---------------------------------------------");
}
Thanks to anyone having a look at this and maybe point me in the right direction!
The indices for parameters in a PreparedStatement start at 1, not at 0.
So the first parameter has index 1. If you try to use 0 as an index, it will complain that that's not a valid index.
PreparedStatement parameter indexes start at 1 - so you probably just want
setString(j + 1, params[j]);
etc
The index of the first parameter is 1, not 0
try to use
System.out.println("Problem constructing callableStatement: "+e.getMessage);
to find out the stacktrace and the "trouble" line of code.
} else if (paramTypes[j]
Shouldn't that be params[ j ]?

Categories