Throw Simple Exception in Java
I'm looking to learn how to throw a super simple exception in java. I have the following:
public Percolation(int N) // create N-by-N grid, with all sites blocked
{
if(N < 1)
throw new Exception("N must be greater than zero.");
grid = new boolean[N * N + 2];
dimension = N;
grid[0] = true;
grid[N+1] = true;
unionStruct = new QuickFindUF(N+2);
}
It's not compiling, but t开发者_开发技巧hat's the type of thing I'm looking to do. What's the proper syntax to do this?
It's because you're throwing a checked exception without declaring the exception you're throwing. In your case you should probably be throwing an exception derived from RuntimeException instead, and these are not checked (meaning you don't have to declare them). So the two ways to fix this are
throw new IllegalArgumentException("N must be greater than zero."); // unchecked
or
public Percolation(int N) throws Exception
I suspect that you are not specifying that an exception is being thrown. Tell us what error you recieve.
In the meantime, try this:
public Percolation(int N) throws Exception
{
if(N < 1)
throw new Exception("N must be greater than zero.");
...
There are two types of exceptions in Java:
- Compiler enforced exceptions ("checked exceptions").
- Runtime exceptions ("unchecked exceptions").
Either throw an unchecked exception, or specify that your exception is thrown, as I've done in the code above.
In this case, the unchecked exception you are looking for would be IllegalArgumentException
.
You have to declare that the constructor throws an Exception
public Percolation(int N) throws Exception {} //create N-by-N grid, with all sites blocked
精彩评论