• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

java exception causes object to disappear  RSS feed

 
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.
 
Rancher
Posts: 1896
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: 1896
15
Android Eclipse IDE Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are most welcome.
 
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!