[Logo]
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.
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards


This thread has been viewed 377 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jan 16, 2018 12:39:05.