Forums Register Login
java exception causes object to disappear
I have a Matrix class whose constructor throws an IllegalArgument exception if the matrix dimensions are not right. The exception is being caught in my main method. An odd thing happens when I put try-catch block though. If I create a matrix object (valid dimensions are passed) and put it in a try block, once the code goes past the catch block, the matrix object can no longer be referenced. The compiler issues an error that the symbol does not exist. Look below at my code please. The error goes away if I remove the try-catch block.
The issue is not with try block, rather the issue is with scope of the variable. You are declaring it inside try block, so the scope is limited to the try block. You should have declared it outside try block like this
Thanks, that worked!!
You are most welcome.
Do note, though, that in that particular example if an exception was thrown when creating the matrix M2 would still be null. Which means that it would throw a NullPointerException when you try and call a method on it. If the try/catch block is there to catch constructor errors then there is no point trying to refer to the object you create outside the try/catch block.

This thread has been viewed 442 times.

All times above are in ranch (not your local) time.
The current ranch time is
Dec 10, 2018 14:31:37.