简体   繁体   中英

Why won't the following java code compile?

Quite Frankly, I'm just not understanding what my instructor is asking me to do here. I've tried using "try - catch" blocks, as well as throws Exception in the method signature. I've read about checked and unchecked exceptions. I'm sure this will get voted down or closed, but can someone throw me a bone here? My instructors instructions are as follows:

"Correct it so it compiles."

class Exception3{
    public static void main(String[] args){         
    if (Integer.parseInt(args[0]) == 0)             
        throw new Exception("Invalid Command Line Argument");     
     } 
}

It's obvious that it is throwing a RuntimeException. More Specifically an ArrayIndexOutOfBoundsException. I know the cause of the exception is because the array is empty, so the referenced index doesn't exist. I mean, technically I could just erase if(Integer.parseInt(args[0]) == 0) and throw new Exception("Invalid Command Line Argument"); and replace it with System.out.println("It compiles now");

Any ideas?

public static void main(String[] args) throws Exception{         
    if (Integer.parseInt(args[0]) == 0)             
        throw new Exception("Invalid Command Line Argument");     
     } 

Your method throwing Exception , so method declaration should specify that it may throw Exception .

As per java tutorial

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

You have to either catch it using a try catch statement:

class Exception3 {
    public static void main(String[] args) {
        try {
            if (Integer.parseInt(args[0]) == 0)
                throw new Exception("Invalid Command Line Argument");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

or declare it at the method header:

class Exception3 {
    public static void main(String[] args) throws Exception {
        if (Integer.parseInt(args[0]) == 0)
            throw new Exception("Invalid Command Line Argument");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM