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.
-
1Why wouldn't `IllegalArgumentException` work? – Sep 24 '12 at 18:00
4 Answers
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.

- 714,442
- 84
- 1,110
- 1,523
-
-
4@Eng.Fouad My understanding is that the OP plans to *throw* this exception in his library, rather than catching it. – Sergey Kalinichenko Sep 24 '12 at 18:03
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

- 1
- 1

- 11,982
- 40
- 122
- 216
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.

- 14,968
- 5
- 37
- 59
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.

- 387
- 3
- 13