Reputation: 151
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?
Upvotes: 1
Views: 248
Reputation: 3181
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");
}
}
Upvotes: 3
Reputation: 66637
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.
Upvotes: 7