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
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.