Why won't this method print the message in the exception parameter? - java

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

Related

how to use throws Exception? [closed]

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

How do I Throw an IllegalArgumentException that won't terminate my program?

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.

Java catch Exception IllegalArguementsException forces me to initiate string

Whenever I catch the exception for the integer it works fine, but when I try with the string value it wants me to initiate the string. The follow is my code so far
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LocalMath e = new LocalMath();
Machine machine = new Machine(name);
String name;
int age;
Scanner userInput = new Scanner(System.in);
System.out.println("What is your name?");
try{
name = userInput.nextLine();
} catch (Exception IllegalArgumentException) {
System.out.println("Must be a character from the english alphabet!");
}
// System.out.println(e.add(5, 10));
System.out.println(name);
System.out.println("-------");
System.out.println("What is your age?");
try {
age = userInput.nextInt();
System.out.println(age);
} catch (Exception IllegalArgumentException) {
System.out.println("Must be in numeric value only!");
}
}
}
And the rest of my code
public class Machine {
public Machine(){
}
public Machine(String name){
}
public Machine(int age){
}
}
Just initialize your String variable to null
String name = null;
It's possible because of the try/catch block for name to get to the sysytem.out line without any value being assigned to it. For example, if userInput.nextLine() raises an illegal argument exception, name will not be assigned a value, yet the rest of the function will execute because the exception is caught. Anything that happens between the exception and the catch line is skipped. Thus, the String "name" could be used before anything is assigned to it; the compiler is therefore forcing you to explicitly initiliaze it.
If you could use the variable/memory address without guaranteeing it had been set to a value first, you might find "name" holding erroneous data from the last time that memory address was used. The compiler is guaranteeing that can't happen.
First, you could declare String name = null; before you instantiate your Machine object.
However, you should instantiate the Machine object after you assign a value other than null to machine. For example, as you have it now, you're creating a machine object with a name of null passed into the constructor.
I would instantiate your machine like this:
try{
name = userInput.nextLine();
} catch (Exception IllegalArgumentException) {
System.out.println("Must be a character from the english alphabet!");
}
Machine machine = new Machine(name);
One more thing, I don't think IllegalArgumentException will prevent the user from entering a number as part of the name. "Bob1234" is a valid string, so you won't catch the exception in this case.
Instead, you'll have to check each character one at a time.
for (int i = 0; i < name.length(); i++) {
if (isDigit(charAt(i))
throw new IllegalArgumentException("Must be in numeric value only!");
}

How to deal with a specific type of expection

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

exceptions in java

I wrote a code which checks all kinds of conditions.
If it meets the condition it does what it is supposed to, otherwise I want it to throw an
exception.
Is there any special syntax for that? Otherwise the compiler wants me to return any array,
which I don't want to, due to the pre-condition.
Here is part of my code:
public static int [] code(int[]arr){
if ((arr!=null)&&(chack4and5(arr))&&(arr[arr.length-1]!=4)&&(TwoFours(arr))){
int k=0;
for(int i = 0; i<=arr.length-1; i++){
if (arr[i] == 4){
int place= pos(arr,k);
arr[place]=arr[i+1];
arr[i+1]=5;
k=k+3;
}
}
return arr;
}
else {
System.out.println("Please enter a legal array which matches the pre- conditions");
}
}
}
The way to throw an exception is
throw new IllegalArgumentException(
"Please enter a legal array which matches the pre- conditions");
IllegalArgumentException is a Java runtime exception suitable for the current situation, but of course you can choose another one, or create and use your own type too. The only restriction is that it must be a subclass of java.lang.Exception.
I would rearrrange your code though to check the preconditions first, then proceed if everything's fine - I find this more readable:
if (arr == null || !chack4and5(arr) || arr[arr.length-1] == 4 || !TwoFours(arr)) {
throw new IllegalArgumentException(
"Please enter a legal array which matches the pre- conditions");
}
int k=0;
for(int i = 0; i<=arr.length-1; i++){
if (arr[i] == 4){
int place= pos(arr,k);
arr[place]=arr[i+1];
arr[i+1]=5;
k=k+3;
}
}
return arr;
(In fact, I would even prefer extracting the precondition check into a separate method - but I leave this to you.)
throw new IllegalArgumentException(
"Please enter a legal array which matches the pre- conditions")
java.langIllegalArgumentException is a RuntimeException that means some of the arguments are not as they are expected to be. Since it is an unchecked exceptions, your callers are not forced to handle it in any way (as opposed to checked exceptions)
You can throw an Exception by yourself. Maybe the best way to do this is defining a custom exception and then throwing it. If you don't want to do that use an IllegalArgumentException.
Here an example of a custom exception:
public static int [] code(int[]arr) {
if ((arr!=null)&&(chack4and5(arr))&&(arr[arr.length-1]!=4)&&(TwoFours(arr))){
int k=0;
for(int i = 0; i<=arr.length-1; i++){
if (arr[i] == 4){
int place= pos(arr,k);
arr[place]=arr[i+1];
arr[i+1]=5;
k=k+3;
}
}
return arr;
}
else {
throw new MyException("No legal array");
}
}
}
And here your custom exception:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
If the exception is that something about your arguments is illegal, then throw an IllegalArgumentException:
throw new IllegalArgumentException("descriptive message")
You may want to take a look at Oracle's tutorials on exceptions.
To throw an exception, you use the throw keyword.
To mark that a method may throw an exception, use the throws keyword, like
public static void foo() throws SomeException
You can throw exception with this line
throw new SomeKindOfException("Exception description"); // or any other exception, also yours...
But you need to specify at the method declaration:
public static int [] code(int[]arr) throws SomeKindOfException{
See Oracle tutorial for more

Categories

Resources