Reputation: 2040
I would like to raise an error and terminate a Java program, but I am confused how to do it, as it seems to be fundamentally different from how I would do it in Python.
In Python I would write:
import sys
if len(sys.argv) != 2:
raise IOError("Please check that there are two command line arguments")
Which would generate :
Traceback (most recent call last):
File "<pyshell#26>", line 2, in <module>
raise OSError("Please check that there are two command line arguments")
OSError: Please check that there are two command line arguments
This is what I would like as I am not trying to catch the error.
In Java, I try to do something similar:
public class Example {
public static void main (String[] args){
int argLength = args.length;
if (argLength != 2) {
throw IOException("Please check that there are two command line arguments");
}
}
}
However NetBeans tells me that it "cannot find symbol" IOException
I have found these answers for throwing exceptions:
How to throw again IOException in java?
But they both recomend defining whole new classes. Is this necessary? Even though IOException belongs to the Throwable class?
My fundamental misunderstanding of the difference between Python and Java are hindering me here. How do I basically achieve what I have achieved with my python example? What is the closest replication of that error raising in Java?
Thank you
Upvotes: 0
Views: 183
Reputation: 8587
IOException
belongs to the java.io
package, you should import it first. It is also a "checked" exception, which means that you should either modify your main
method, adding throws IOException
, or catch it in the method body.
import java.io.IOException;
public class Example {
public static void main(String [] args) throws IOException {
...
throw new IOException("Please check that...");
}
}
I agree with @pbabcdefp that you should use IllegalArgumentException
which is a RuntimeException
and does not need to be handled explicitly in the code.
Upvotes: 1