Reputation: 4129
I'm writing a program that will perform matrix operations, and I'm trying to figure out what kind of exeption I should use in case of invalid dimensions. Is there some exception type that already exists that would be acceptable for my operations to throw; or should I implement my own exception type? I know that pretty much any exception type would do what I want, but the issue is making sure that the exception actually describes the problem that caused it.
Upvotes: 5
Views: 234
Reputation: 397
If You can use your own exception. then Your own exception should extends java.lang.RuntimeException or subclass of RuntimeException. RuntimeException is unchecked exception. You should use unchecked exception in this case.
Upvotes: 0
Reputation: 15240
You can throw an IllegalArgumentException(String message) with the message describing that the matrix dimensions are not suitable for what are you trying to do.
For example you should throw such an exception if your library users are trying to call a method that works only on nXn
matrices with a nXm
matrix argument.
Upvotes: 2
Reputation: 726559
The closest fit for what you are looking for is the IndexOutOfBoundsException
. You can use it as-is, or derive your own MatrixIndexOutOfBoundsException
exception from it.
Upvotes: 7
Reputation: 12484
Like others say, you probably don't need to. But since customer is always right - You should create your own exception type.
Here's a related SO question though : Exception in thread "main" java.lang.RuntimeException: Matrix is singular
Upvotes: 2