• Post Reply Bookmark Topic Watch Topic
  • New Topic

java exception causes object to disappear  RSS feed

 
Nazma Panjwani
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Swastik Dey
Rancher
Posts: 1812
15
Android Eclipse IDE Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nazma Panjwani
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, that worked!!
 
Swastik Dey
Rancher
Posts: 1812
15
Android Eclipse IDE Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are most welcome.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!