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
Related
I have a sample program which registers people for an airline.
At the Registration class, on the selectSeats method, I have a try catch block, where the catch statement should catch InputMismatchException in case the user inputs a non numeric value.
However, the reinput operation isn't happening, so instead, when an exception happens, the program just throws the error message and proceeds to the end (which leads to unexpected results)
This is the method in question
public void seleccionarAsiento() {
boolean malaSeleccion = true;
do{
try{
System.out.println("\n\n Digite el número de asiento del 0 hasta el 20");
while (malaSeleccion) {
//Selección del hashSet correspondiente a cada vuelo mediante uso de la variable polimorfica "asientos".
if(this.destino.equals("Nicaragua")) {
asientos = asientosNCA;
}
else if (this.destino.equals("Panama") || this.destino.equals("Panamá")) {
asientos = asientosPNA;
}
this.asiento = input.nextInt(); //The part causing the issue
if(this.asiento < 0 || this.asiento > 20) {
System.out.println("\nSelect a seat between 0 and 20.");
} else if (asientos.contains(this.asiento)) {
System.out.println("\nSeat taken, select another one.");
} else if (this.asiento >= 0 && this.asiento <= 20 && asientos.contains(this.asiento) == false) {
asientos.add(this.asiento);
continuarCiclo = false;
malaSeleccion = false;
}
}
} // Fin de bloque try
//Bloque catch para prevenir un input no numerico.
catch (InputMismatchException inputMismatchException) {
System.out.println("Not numeric value, try again.");
input.nextLine();
}
In case this is relevant, since I'm not sure if this could be related to a problem with Inheritance (but I doubt it because the exception is being caught)
This is the start of the class where that method is, and an extension to Exception I added.
public class RegistroCompra {
Scanner input = new Scanner(System.in);
private String destino;
private int asiento;
private boolean continuarCiclo = true;
public static HashSet<Integer> asientosNCA = new HashSet(21);
public static HashSet<Integer> asientosPNA = new HashSet(21);
HashSet<Integer> asientos = null;
class ExcepcionRegistro extends Exception {
ExcepcionRegistro(String s) {
super(s);
}
}
} while (continuarCiclo == true); // Fin de bloque Do
Edit: I solved the issue by making the method recursive in the catch block.
So if it catches the inputmismatchexception (because it was catching it), it cleans the buffer from the invalid input with input.nextLine() and then, the function calls itself again to restart the selection process.
Do it as follows:
public void selectSeat() {
boolean valid = true;
do {
System.out.println("Enter the seat number from 0 to 20");
// ...
try {
this.asient = Integer.parseInt(input.nextLine());
// ...
} catch (InputMismatchException inputMismatchException) {
System.out.println("This is not a numerical value, try again.");
valid = false;
}
} while (!valid);
}
The exception may not the instance of InputMismatchException. You could try add Exception e to take a look the real exception.
catch (InputMismatchException inputMismatchException) {
System.out.println("Este no es un valor númerico, intente de nuevo.");
input.nextLine();
}
catch (Exception e) {
exception.printStackTrace()
input.nextLine();
}
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.
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 am trying to write a program to equate the value of any number to any power, and I'm suppose to implement exception handling for exponents less than zero which i successfully did and also exception handle for when the value is too large to output i.e. infinity.
heres my power class which contains the function Power :
public class power
{
// instance variables - replace the example below with your own
public static double Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent cannot be less than zero");
}
else if(exp == 0){
return 1;
}
else{
return base * Power(base, exp-1);
}
}
}
Heres the Test class :
public class powerTest
{
public static void main(String [] args)
{
double [] base = {2.0, 3.0, 2.0, 2.0, 4.0 };
int [] exponent = {10, 9, -8, 6400, 53};
for (int i = 0; i < 5; i++) {
try {
double result = power.Power(base[i], exponent[i]);
System.out.println("result " + result);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
}
heres the output of the test :
result 1024.0
result 19683.0
Exponent cannot be less than zero
result Infinity
result 8.112963841460668E31
my question is how can i get "result infinity" to say something else through ArithmeticException handling something along the lines of "Floating point Overflow"?
thanks in advance.
When you catch the exception, here
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
just do
System.out.println("Floating point Overflow")
as well(if you want to add more) or replace the first print with this statement
This way like you said, "you get result infinity" to say something else through ArithmeticException handling"
Not sure if this is what you are looking for, but you can test for infinity/overflow with an if statement as well:
if( mfloat == Float.POSITIVE_INFINITY ){
// handle infinite case, throw exception, etc.
}
So in your situation, you would do something like this:
public static double
Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent less than zero");
}
else if(exp == 0){
return 1;
}
else{
double returnValue = base * Power(base, exp-1);
if(returnValue == Double.POSITIVE_INFINITY)
throw new ArithmeticException("Double overflowed");
return returnValue;
}
}