Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find symbol IllegalArgumentException

Tags:

java

I have a very simple program that tries to throw an exception. The compiler says it cannot find IllegalArgumentException even though it didm't say anything about that name when I put it in the throw specifier part:

import java.lang.*;

class A
{
    public A() throws IllegalArgumentException
    {
        if (n <= 0)
            throw IllegalArgumentException("n is less than 0");
    }
}

Here's the error:

Main.java:28: error: cannot find symbol
            throw IllegalArgumentException("n is less than 0");
                  ^
  symbol:   method IllegalArgumentException(String)
  location: class A
1 error

I realize this is very simple (my very first attempt at writing Java). I've tried looking for answers but they haven't helped me to a solution.

like image 456
template boy Avatar asked Sep 18 '14 20:09

template boy


People also ask

What to do if Cannot find symbol in Java?

In the above program, "Cannot find symbol" error will occur because “sum” is not declared. In order to solve the error, we need to define “int sum = n1+n2” before using the variable sum.

What is error Cannot find symbol?

The cannot find symbol error, also found under the names of symbol not found and cannot resolve symbol , is a Java compile-time error which emerges whenever there is an identifier in the source code which the compiler is unable to work out what it refers to.

Can you catch IllegalArgumentException?

IllegalArgumentException is an unchecked Java exception (a.k.a. runtime exception). It derives from RuntimeException , which is the base class for all unchecked exceptions in Java. Because IllegalArgumentException is an unchecked exception, the Java compiler doesn't force you to catch it.


1 Answers

Use the new keyword

public A() {
    int n = ...;
    if (n <= 0) {
        throw new IllegalArgumentException("n is less than 0");
    }
}
like image 100
Reimeus Avatar answered Oct 09 '22 22:10

Reimeus