Ok so I have a method with a switch statement but I left out the rest of the cases because they're not important. In my main method, the operator method is called and passed the parameter "selection" in a while loop until they choose "Q".
When the user enters a negative number, it should throw an exception, print a message, and ignore their input but then loop back to the beginning. When this exception is thrown it terminates the program. Any help would be very much appreciated. Thanks!
public static void operator(String selection) throws IllegalArgumentException{
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
if(input.nextDouble()<0){
throw new IllegalArgumentException("Price cannot be a negative value");
}
else{
price = input.nextDouble();
}
break;
case"Q":
System.exit(0);
}
}
An IllegalArgumentException inherits from RuntimeException, for it not to stop your program you can just use a simple try{} catch {} but i don't recommend doing that with Runtime Exceptions. If that's the case, create your own Exception inheriting from java.lang.Exception.
You can use try catch here.
Something like this should work:
public static void operator(String selection) {
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
try {
if(input.nextDouble()<0) {
throw new NegativePriceException();
}
} catch (NegativePriceException e) {
System.out.println("The price can't be negative.");
e.printStackTrace();
}
price = input.nextDouble();
break;
case"Q":
System.exit(0);
}
}
And to make your own Exception class you basically need to inherit from Exception (if you want to use try catch on it) or inherit from RuntimeException (if you want it to stop your program from running), like this:
public class NegativePriceException extends Exception {
public NegativePriceException() {
super();
}
}
Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.
In your main method you should handle the Exception
public static void main(String args[]) {
//codes
try{
operator("A");
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
}
You've gotten some good answers already on how to handle the exception.
For your case I don't think an exception is appropriate at all. You should get rid of the exception altogether and just handle the problem input by printing an error message and asking for a new input.
Exceptions are for exceptional situations, they should not be part of the normal execution of your code.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
this is my class Person() method inputPersonInfo():
Scanner sc = new Scanner(System.in);
System.out.println("Input Information of Person");
System.out.println("Please input name");
name = checkInputString();
System.out.println("Please input address");
address = checkInputString();
System.out.println("Please input salary");
salary = checkInputSalary();
return new Person(name,address,salary);
}
this is my check for input method:
public static String checkInputString() {
//loop until user input true value
while (true) {
String s = in.nextLine();
if (s.isEmpty()) {
System.err.println("Not empty.");
} else {
return s;
}
}
}
// check if salary is smaller than 0
public static double checkInputSalary() {
//loop until user input true value
while (true) {
try {
double salary = Double.parseDouble(in.nextLine());
if (salary < 0) {
System.err.println("Salary is greater than zero");
System.out.print("Please input salary: ");
} else {
return salary;
}
} catch (NumberFormatException ex) {
System.err.println("You must input digidt.");
System.out.print("Please input salary: ");
}
}
}
how can i throws Exception in this method without using the above checkinput method() ?
public Person inputPersonInfo (String name, String address, Double salary) throws Exception {}
this is my main class(), do i need to throw any Exception in my main class ?:
System.out.println("=====Management Person programer=====");
//call constructor Person
Person p = new Person();
//enter 3 person
for (int i =0; i< 3 ;i++){
persons[i] = p.inputPersonInfo(p.getName(), p.getAddress(), p.getSalary());
}
throws Exception is used when defining a method to signal that this method may throw an error in case something does not go right. It is simply a signal, it does not handle anything.
In case you add this to a method declaration, wherever you call this method, you will be required (by the IDE, compiler..) to add handling mechanisms, such as a try-catch clause, or add yet another throws Exception to the declaration of the method that is calling your "dangerous" method.
Example:
public void dangerousMethod() throws Exception, RuntimeException // Or whatever other exception
{
throw new Exception("FAKE BUT DANGEROUS");
}
public void anotherMethod()
{
dangerousMethod(); // <------------ Compiler, IDE will complain that this should be handled in some way
// Either add try catch:
try
{
dangerousMethod();
}
catch(Exception e) // Or whatever specific Exception you have
{
// Handle it...
}
// Or add the throws Exception at the head of the anotherMethod()
}
For unchecked exception:
NumberFormatException is a RuntimeException, which is an "unchecked exception", that means even if you don't try...catch it, it will eventually thrown to the outside (the caller).
In the outside (the caller), you can try...catch it if you want so, or you can ignore it. If the exception happens, it will be thrown out. If your program is a console program, it will be thrown and displays in the console window.
That also means your main method don't have to explicitly try..catch or throws it, and the compiler will still compile it successfully.
For checked exception:
On the other side, about the "checked exception", you have to try..catch or else the compiler will show you errors. If you do not want to try...catch the exception in the current method, you can use throws Exception in the method signature. For e.g with IOException:
public Person inputPersonInfo (String name, String address, Double salary) throws IOException {}
In your main method that is calling the above inputPersonInfo(), you have to try..catch or throws it in the main method signature.
For e.g: with IOException (a checked exception)
public static void main(String[] args) throws IOException {
...
inputPersonInfo(...);
...
}
Create the method so that Exceptions won't be thrown to begin with:
public double getSalaryFromUser() {
String salary = "";
while (salary.isEmpty()) {
System.out.print("Please enter a Salary amount: --> ");
salary = in.nextLine();
/* Input Validation:
The RegEx below used as argument for the String#matches()
method checks to see if the supplied string is a unsigned
Integer or floating point numerical value. If anything other
than that is supplied then the error message is displayed.
The second condition checks to see if the value is greater
than 0.9d */
if (!salary.matches("\\d+(\\.\\d+)?") || Double.valueOf(salary) < 1.0d) {
System.out.println("Invalid Entry (" + salary + ")! You must supply a");
System.out.println("numerical value and it must be greater than zero.");
System.out.println("Try again...");
System.out.println();
salary = "";
}
}
return Double.parseDouble(salary);
}
I'm writing a method that is supposed to convert a string to an int if possible, and it throw an exception of not possible with a message. It throws the exception but it doesn't print the message, meaning it acts identically as it would were I to comment out the exception condition:
private static int throwsMethod() throws NumberFormatException{
Scanner s = new Scanner(System.in);
System.out.println("enter a number");
String intNumber = s.next();
Integer wrapperIntNumberConv = Integer.parseInt(intNumber);
if(!(wrapperIntNumberConv instanceof Integer)){
throw new NumberFormatException("can't make an int");
}
int fullConvertedNumber = (int) wrapperIntNumberConv;
System.out.println(fullConvertedNumber);
return fullConvertedNumber;
}
how can I do it without a try/catch block (I'm trying to learn exceptions and in this exercise, without a try/catch block) and get it to show the message?
edit: the reason the suggested answer that azro put in didn't solve my problem is because nothing there addreses a method with a throws someException() in the header
The exception is probably thrown at this line:
Integer wrapperIntNumberConv = Integer.parseInt(intNumber);
Because parseInt itself throws it if the string does not contain a parsable integer. (Documentation)
So the program does not reach your if in that case.
You need to wrap the line with parseInt inside a try-catch block to be able to throw an exception with your message:
String intNumber = s.next();
try {
return Integer.parseInt(intNumber);
catch(NumberFormatException e) { // catch system's exception
// throw new one with your message
throw new NumberFormatException("can't make an int");
}
Or, you can check if the string contains a number (optional sign and digits), before calling parseInt:
String intNumber = s.next();
if (intNumber.matches("-?\\d+")) { // see: regular expressions
return Integer.parseInt(intNumber);
} else {
throw new NumberFormatException("can't make an int");
}
I'm not sure to understand what you want: if the NumberFormatException is thrown, it can't reach the print instructions
int fullConvertedNumber = (int) wrapperIntNumberConv;
System.out.println(fullConvertedNumber);
return fullConvertedNumber;
so no message is printed.
If you want to print the "can't make an int" message you can print it before throwing the Exception or in the caller method via try-catch
class A{
public static void main(String[]args){
int = 0;
try{
i = Integer.parseInt(args[0]);
}
catch()
System.out.println("this value of i is" + i);
}
How can I print exception using toString if a exception occurs. I am assuming of only one command line argument here.
If you look at the documentation for Integer.parseInt, you will find that it throws NumberFormatException:
Throws:
NumberFormatException - if the string does not contain a parsable integer.
Hence, that is the exception you will want to catch:
try{
i = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {
// handle exception
}
If you want to print out this exception if it is encountered, you could use nfe.printStackTrace().
Usually the catch portion has the exception as a parameter. It's illustrated atop this page: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
I had some difficulty with the title, wasn't sure how to word it more accurately.
I'm having this issue, I have a several methods which ask the user for 3 Double inputs.
For each input it checks if it's valid (for example if its a positive value), if it's not it throws an IllegalArgumentException. Now I made a Tester class to check if the methods are working properly. It's supposed to catch the exception thrown by the methods and re-ask the user for the input which caused that specific exception.
All 3 methods throw and IllegalArgumentException but the error message is different for each one. Is there anyway (when catching the exception) to see which input cause the error? Here's a sample of my code:
public class account
{
double value;
public account(double initialValue)
{
if (initialValue < 0)
{
throw new IllegalArgumentException("Initial value cannot be negative.");
}
value = initialValue;
}
public add(double addValue)
{
if (addValue < 0)
{
throw new IllegalArgumentException("Added value cannot be negative.");
}
value = value + addValue;
}
}
and the tester class would be something like:
public class accountTester
{
public static void main(String[] args)
{
try
{
double initialValue = Double.parseDouble(JOptionPane.showInputDialog("Enter initial value"));
account acc = new account(initialValue);
double addValue = Double.parseDouble(JOptionPane.showInputDialog("Enter value to add"));
acc.add(addValue);
} catch (Exception e) {
System.out.println("Wrong ammount");
initialValue = Double.parseDouble(JOptionPane.showInputDialog("Re-enter ammount"));
}
}
So what would I have to change in the tester class to throw that code only if the IllegalArgumentException is "Initial value cannot be negative."
Sorry if I made this hard to understand.
EDIT: According to my prof, we're supposed to use do
String error = e.toString;
if (error.contains("Added value cannot be negative.")
{
//DO CODE FOR FIRST ERROR
}
I know this isn't the most proper way of doing it though.
Since you can't match over Strings like you would do in a functional language you have to provide three different kind of objects if you want to be able to distinguish them using the try-catch mechanics.
Or with a simplified approach attach a parameter to the exception so that you can use just a catch clause but you could behave differently. Something like
class MyIllegalArgumentException extends IllegalArgumentException {
public int whichParameter;
public MyIllegalArgumentException(String string, int which) {
super(string);
whichParameter = which;
}
}
now you can:
catch (MyIllegalArgumentException e) {
if (e.whichParameter == 0)
..
else if (e.whichParameter == 1)
..
}
You could also check the string for equality but this would be really not a good design choice, you could also have many try-catch blocks but this is not always possible.
After having expanded your code the solution is easy:
public static void main(String[] args) {
try {
double initialValue = ...
account acc = new account(initialValue);
} catch (IllegalArgumentException e) {
...
}
try {
double addValue = ...
acc.add(addValue);
} catch (Exception e) {
System.out.println("Wrong ammount");
initialValue = Double.parseDouble(JOptionPane.showInputDialog("Re-enter ammount"));
}
}
Surround each method call with its own try/catch block?
In your catch block you should only catch IllegalArgumentException. Then what you can do is invoke the getMessage() function which will enable you to do a very simple String.equals call.
Consider this simple program. The program has two files:
File Vehicle.java
class Vehicle {
private int speed = 0;
private int maxSpeed = 100;
public int getSpeed()
{
return speed;
}
public int getMaxSpeed()
{
return maxSpeed;
}
public void speedUp(int increment)
{
if(speed + increment > maxSpeed){
// Throw exception
}else{
speed += increment;
}
}
public void speedDown(int decrement)
{
if(speed - decrement < 0){
// Throw exception
}else{
speed -= decrement;
}
}
}
File HelloWorld.java
public class HelloWorld {
/**
* #param args
*/
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
// Do something
// Print something useful, TODO
System.out.println(v1.getSpeed());
}
}
As you can see in the first class, I have added a comment ("// throw exception") where I would like to throw an exception. Do I have to define my own class for exceptions or is there some general exception class in Java I can use?
You could create your own Exception class:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
In your code:
throw new InvalidSpeedException("TOO HIGH");
You could use IllegalArgumentException:
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
Well, there are lots of exceptions to throw, but here is how you throw an exception:
throw new IllegalArgumentException("INVALID");
Also, yes, you can create your own custom exceptions.
A note about exceptions. When you throw an exception (like above) and you catch the exception: the String that you supply in the exception can be accessed throw the getMessage() method.
try{
methodThatThrowsException();
}catch(IllegalArgumentException e)
{
e.getMessage();
}
It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");
The simplest way to do it would be something like:
throw new java.lang.Exception();
However, the following lines would be unreachable in your code. So, we have two ways:
Throw a generic exception at the bottom of the method.
Throw a custom exception in case you don't want to do 1.
Java has a large number of built-in exceptions for different scenarios.
In this case, you should throw an IllegalArgumentException, since the problem is that the caller passed a bad parameter.
You can define your own exception class extending java.lang.Exception (that's for a checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught.
The other solution is to review the Java API and finding an appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException.
It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.