Catching IllegalArgumentException?

try catch java
throw illegalargumentexception
illegalargumentexception java 8
import illegalargumentexception
illegalargumentexception android
illegalargumentexception checked
catch multiple exceptions java
illegalargumentexception checked or unchecked

I am having a little bit of a problem here. I am trying to figure out how to catch the IllegalArgumentException. For my program, if the user enters a negative integer, the program should catch the IllegalArgumentException and ask the user if he/she wants to try again. But when the exception is thrown, it doesn't give that option. It just terminates. I tried to use the try and catch method but it doesn't work for me. How do I catch this particular exception to continue to run instead of terminating?

public static void main(String[] args) throws IllegalArgumentException
{
    String keepGoing = "y";
    Scanner scan = new Scanner(System.in);
    while(keepGoing.equals("y") || keepGoing.equals("Y"))
    {
        System.out.println("Enter an integer: ");
        int val = scan.nextInt();
        if (val < 0)
        {
            throw new IllegalArgumentException
            ("value must be non-negative");
        }
        System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
        System.out.println("Another factorial? (y/n)");
        keepGoing = scan.next();
    }
}

}

and

public class MathUtils
{
    public static int factorial(int n)
    {
        int fac = 1;
        for(int i = n; i > 0; i--)
        {
            fac *= i;
        }
        return fac;
    }
}

You need to add the try catch block inside the loop to continue the working for the loop. Once it hits the illegal argument exception catch it in catch block and ask if the user wants to continue

import java.util.Scanner;

public class Test {
public static void main(String[] args) 
{
String keepGoing = "y";
populate(keepGoing);

}

static void populate( String keepGoing){
  Scanner scan = new Scanner(System.in);
 while(keepGoing.equalsIgnoreCase("y")){
     try{
        System.out.println("Enter an integer: ");
        int val = scan.nextInt();
        if (val < 0)
        {
            throw new IllegalArgumentException
            ("value must be non-negative");
        }
        System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
        System.out.println("Another factorial? (y/n)");
        keepGoing = scan.next();
    }
    catch(IllegalArgumentException i){
        System.out.println("Negative encouneterd. Want to Continue");
        keepGoing = scan.next();
        if(keepGoing.equalsIgnoreCase("Y")){
        populate(keepGoing);
        }
    }
    }
}
}

Hope this helps. Happy Learning :)

Java Exception Handling - IllegalArgumentException, If we want to catch the IllegalArgumentException then we can use try-catch blocks. By doing like this we can handle some situations. Suppose in catch block if we put code to give another chance to the user to input again instead of stopping the execution especially in case of looping. If we want to catch the IllegalArgumentException then we can use try-catch blocks. By doing like this we can handle some situations. Suppose in catch block if we put code to give another chance to the user to input again instead of stopping the execution especially in case of looping. Example2

I don't think you want your main() method to be throwing an exception. Typically, this is the kind of thing that you'd put in try and catch blocks.

Honestly though, for this sort of thing an if/else would work better. (Unless you're just doing this as a toy example, to learn exceptions.)

Make another method called getNumber() that throws the IllegalArgumentException, that returns an int. Then put it inside the try/catch in the main().

How to solve an IllegalArgumentException in Java?, try { doSomething(); } catch (NumberFormatException e) { // handle the NumberFormatException log.error(e); } catch (IllegalArgumentException� The IllegalArgumentException is intended to be used anytime a method is called with any argument (s) that is improper, for whatever reason. We’ll spend the few minutes of this article exploring the IllegalArgumentException in greater detail by examining where it resides in the Java Exception Hierarchy.

public static void main(String[] args)
{
    String keepGoing = "y";
    Scanner scan = new Scanner(System.in);
    while(keepGoing.equals("y") || keepGoing.equals("Y"))
    {
        int val = 0;
        boolean flag=true;
        while(flag){

            try{
                System.out.println("Enter an integer: ");
                val = scan.nextInt();
                if (val < 0)
                {
                    throw new IllegalArgumentException
                    ("value must be non-negative");
                }
                flag = false;
            } catch(IllegalArgumentException e){
                System.out.println("value must be non-negative");

            }
        }
        System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
        System.out.println("Another factorial? (y/n)");
        keepGoing = scan.next();
    }
}

}

7 Common Mistakes You Should Avoid When Handling Java , However, Java makes it possible to "catch" such errors and program a response An IllegalArgumentException can occur when an illegal value is passed as a� If we want to catch the IllegalArgumentException then we can use try catch blocks. By doing like this we can handle some situations. Suppose in catch block if we put code to give another chance to the user to input again instead of stopping the execution especially in case of looping.

I would suggest you add a test on the negative value and display your message on the spot, then use an else block. Also, you could use String.equalsIgnoreCase() in your loop test like

String keepGoing = "y";
Scanner scan = new Scanner(System.in);
while (keepGoing.equalsIgnoreCase("y")) {
    System.out.println("Enter an integer: ");
    int val = scan.nextInt();
    if (val < 0) {
        System.out.println("value must be non-negative");
    } else { // <-- skip negative value
        System.out.println("Factorial (" + val + ") = "
                + MathUtils.factorial(val));
    }
    System.out.println("Another factorial? (y/n)");
    keepGoing = scan.next();
}

Also, an int factorial(int) method can only the first 12 correct values. You could use a long or a BigInteger like

public static BigInteger factorial(int n) {
    BigInteger fac = BigInteger.ONE;
    for (int i = n; i > 1; i--) {
        fac = fac.multiply(BigInteger.valueOf(i));
    }
    return fac;
}

Javanotes 8.1, Section 3.7 -- Introduction to Exceptions and try..catch, We can simply throw an IllegalArgumentException or NullPointerException We can catch the checked exception and throw an unchecked RuntimeException� public IllegalArgumentException(String message, Throwable cause) Constructs a new exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this exception's detail message.

Similar to some other answers, I would say that your main() method should not throw an exception to display an error message to the user, because that is not the purpose of exception handling mechanisms in Java. Exception handling is designed to enable methods to signal that something happened that should not have happened, so the methods that call those methods will know that they need to deal with them. In general, exceptions are caught, not thrown, by main() methods and other user interface methods.

I would make the method factorial() throw the IllegalArgumentException, rather than your main() method in your program class. Your main() method should use try and catch to handle this exception. With this design, if someone else wanted to use your MathUtils class, they would know that your factorial() method throws an IllegalArgumentException (especially if you document your code with javadoc), and would write their code to handle the exception. In the current situation, if someone tries to call MathUtils.factorial(-1), the return value would be 1 because the for loop inside factorial() would not execute at all (because i is initially set to -1, which is not greater than 0).

This is how I would revise your code:

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String keepGoing = "y";

        while(keepGoing.equalsIgnoreCase("y")) {
            try { // This code might throw an exception
                System.out.println("Enter an integer: ");
                int val = scan.nextInt();
                System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
                System.out.println("Another factorial? (y/n)");
                keepGoing = scan.next();
            } catch (IllegalArgumentException | InputMismatchException e) {
                /* An InputMismatchException is thrown if the input is not an integer.
                   See the documentation for Scanner method nextInt() for more details.
                */
                System.out.println("You must enter a non-negative integer.");
                System.out.println("Try again? (y/n)");
                keepGoing = scan.next();
            }
        }
    }
}

and

public class MathUtils throws IllegalArgumentException {
    public static int factorial(int n) {
        if (fac < 0) {
            throw new IllegalArgumentException("value must be non-negative");
        }
        int fac = 1;
        for(int i = n; i > 0; i--) {
            fac *= i;
        }
        return fac;
    }
}

Throwing an exception in Java, After the native code catches and handles an exception, it can either clear the pending It is this IllegalArgumentException that the Java code which invoked the� Today we make our way to the IllegalStateException in Java, as we continue our journey through Java Exception Handling series. The “proper” use of the IllegalStateException class is somewhat subjective, since the official documentation simply states that such an exception “signals that a method has been invoked at an illegal or inappropriate time.

Catching and Throwing Exceptions, However, Java makes it possible to "catch" such errors and program a response An IllegalArgumentException can occur when an illegal value is passed as a� The Catch Block. You can implement the handling for one or more exception types within a catch block. As you can see in the following code snippet, the catch clause gets the exception as a parameter. You can reference it within the catch block by the parameter name.

Javanotes 7.0, Section 3.7 -- Introduction to Exceptions and try..catch, There may be zero or more catch blocks. finally block may be omitted. However at least one throw IllegalArgumentException("Name required"). The type of the � Handling an exception is one of the most common but not necessarily one of the easiest tasks. It is still one of the frequently discussed topics in experienced teams, and there are several best practices and common mistakes you should be aware of.

Exceptions: try, catch, finally, throw, Nothing, IllegalArgumentException is one of the exception classes defined in the Java class If you throw an exception, and don't catch it in the same method, then that � If, within one try statement you want to have catch clauses of the following types, in which order should they appear in your program: (1) Exception (2) IllegalArgumentException (3) RuntimeException (4) Throwable A) 1, 2, 3, 4 B) 2, 3, 1, 4 C) 4, 1, 3, 2 D) 3, 1, 2, 4

Comments
  • Not quite related to your question, but int is probably not the best data type to use for a factorial. The largest factorial that fits into an int is 12!.
  • The simplest option is to not throw the Exception in the first place.
  • @PeterLawrey It's probably a school assignment where the teacher has instructed them to do so. Yay to another generation of programmers learning to use exceptions where they shouldn't.
  • If you have to use try/catch, you can put it inside the while() loop.
  • Throwing explicitly within a try block is an example of using exceptions for control flow, which is bad practice. See item 57 of Josh Bloch's Effective Java.
  • Nesting two loops, both with essentially the same condition (that is, we need to keep going) just to catch one exception seems far more complicated than it needs to be. Why not just have a single loop and catch the exception near the bottom of it?