Java question (declaring a variable in try-catch blocks)

Status
Not open for further replies.

orestis

Ars Tribunus Militum
1,598
this code works:

code:<HR>
Code:
 try{<P>      FileInputStream in = new FileInputStream("object.txt");
      ObjectInputStream sIn = new ObjectInputStream(in);<P>      Record read = (Record)sIn.readObject();
      System.out.println(read);<P>    }catch(FileNotFoundException ex1){System.out.println("File not found");}
     catch(IOException ex2){System.out.println("IOException");}
     catch(ClassNotFoundException ex3){System.out.println("ClassNorFound");}

the question is:

how can I use the read object outside the try-catch block ?
it gets out of scope so the compiler prints an error.
I don't want to put everything in the try-catch block as it becomes inefficient and ugly. I don't want to push the exception higher up though. Am I missing something here ? Any suggestions ?
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by GoofBall:
Declare the object outside your try statement.

Exactly, like thus:

code:<HR>
Code:
Record read = null;<P>try {
  ...
  read = (Record)sIn.readObject();
} catch ... { ... }<P>/* Here you can use read */

The initializer (null) is to keep the compiler from complaining that read is possibly unitialized. But, beware that if an exception was thrown by the above code, and the handler allowed control to pass to the code following it, then "read" may possibly be null.

I've found that intelligent exception handling is one of the most difficult things to get right. Large projects, especially, can suffer when stubs or printfs are stuck in initially to get the code to compile, and the exception handling is never revisited.

(kg*m*m)/(s*s)
 

orestis

Ars Tribunus Militum
1,598
Thanks! I knew I had to declare the object outside but the compiler kept complaining. I guess I was too newbie to think about that null reference.

You right, it's my first project (I use it to learn Java) and I'm already confused about what to do with the exceptions. It's VERY tempting just to leave them empty. But that's bad practice, isn't it ? They can be used to do stuff rather than just print "OOPS!".

Maybe I'll start another thread to ask about it...
 

Midlands

Ars Praetorian
535
Subscriptor
Yes -- I would say don't *ever* just leave the catch clause empty, until you're rather advanced and are absolutely sure that's what you want. Otherwise, you'll get an exception, code will silently be skipped, and you'll never know.

Some basic rules -- to be broken once you're positive you've got this stuff cold, but good for now:

- Never, ever leave the 'catch' clause empty.
- Never, ever catch RuntimeException, Error, or Throwable. (Catching a NullPointerException or ArrayIndexOutOfBoundsException is, IMHO, very, very poor style.)
- Declare your throws clauses with the most specific errors possible. (That is, 'throws IOException, ParseException, UserNotFoundException' is vastly preferable to 'throws Exception'.)
- Never, ever just exit without printing something out. There's nothing more aggravating than seeing your Java program vanish (poof!) without telling you why.
- If you're writing main() as a test (and not a real app), just declare it with 'throws Exception'. Very easy, and the JVM will dump the stack trace of any exception that blows past main().
- When creating your own exceptions, subclass a lot, and make them into a real hierarchy. That way they'll actually be useful.
 

Polish Hammer

Wise, Aged Ars Veteran
162
This thread came to mind today when I was having a similar problem: I declared an array, allocating space to hold 3 or 4 objects of a particlular class--I did this just outside of a "try". Within the try, I attempted to call the constructor, passing data from a Result Set from MySQL into the constructor. I received an exception in main, and after debugging I found that it was the Result Set code in the constructor causing the problem--although the code was right, and it worked find just outside the try, it did not work within it. How come? Can you not instantiate objects inside a try statement if the space was allocated to them outside the try?
 

m1sh1

Smack-Fu Master, in training
89
- Never, ever catch RuntimeException, Error, or Throwable. (Catching a NullPointerException or ArrayIndexOutOfBoundsException is, IMHO, very, very poor style.)

Well midlands I am not too sure I completely agree with your second rule of never catching RuntimeExceptions. One of the most common RuntimeExceptions I catch is the NumberFormatException when using something like Integer.parseInt() and not to mention the fact that the SecurityExceptions are RuntimeExceptions. I agree that it is preferrable to do a check of whether the index is greater than or the object is null to catching a NullPointerException or IndexOutOfBoundsException. Still I don't think a rule (even for a newbie) stating that do not catch RuntimeExceptions is a good idea. I completely agree on the Error part though.

edit: spelling
 

Midlands

Ars Praetorian
535
Subscriptor
Originally posted by Polish Hammer:
This thread came to mind today when I was having a similar problem: I declared an array, allocating space to hold 3 or 4 objects of a particlular class--I did this just outside of a "try". Within the try, I attempted to call the constructor, passing data from a Result Set from MySQL into the constructor. I received an exception in main, and after debugging I found that it was the Result Set code in the constructor causing the problem--although the code was right, and it worked find just outside the try, it did not work within it. How come? Can you not instantiate objects inside a try statement if the space was allocated to them outside the try?

No, this shouldn't be an issue. Can you post the code and we'll see what's going on? try { } blocks certainly shouldn't cause this kind of problem.
 

Midlands

Ars Praetorian
535
Subscriptor
Originally posted by m1sh1:
Well midlands I am not too sure I completely agree with your second rule of never catching RuntimeExceptions. One of the most common RuntimeExceptions I catch is the NumberFormatException when using something like Integer.parseInt() and not to mention the fact that the SecurityExceptions are RuntimeExceptions. I agree that it is preferrable to do a check of whether the index is greater than or the object is null to catching a NullPointerException or IndexOutOfBoundsException. Still I don't think a rule (even for a newbie) stating that do not catch RuntimeExceptions is a good idea. I completely agree on the Error part though.

Fair enough. I'd forgotten that a NumberFormatException is a RuntimeException -- and I will strongly state that it never should have been, since you know damn well when you are turning strings into integers and should be prepared to deal with the string containing bogus data.

SecurityExceptions, yes, too, if you're writing security-conscious code. I tend to write server code where we're running without a sandbox, so i ignore this one.

So there are definitely exceptions. However, in general, catching RuntimeExceptions (*especially* "catch (RuntimeException re)", which is what I really meant by my last post) is still a pretty bad idea.
 

m1sh1

Smack-Fu Master, in training
89
midlands wrote:
it never should have been, since you know damn well when you are turning strings into integers and should be prepared to deal with the string containing bogus data

well I agree NumberFormatException might have been better not being derived from IllegalArgumentException and therefore RuntimeException

SecurityExceptions, yes, too, if you're writing security-conscious code
Well I think that SecurityException makes sense as a RuntimeException since most programs are not written with a sandbox in mind which means that you can safely ignore it and not worry about having to catch it and have no idea what to do with it. Let the program crash instead.


However, in general, catching RuntimeExceptions (*especially* "catch (RuntimeException re)", which is what I really meant by my last post) is still a pretty bad idea

I totally agree with this. Worse I was doing a group assingment and this guy instead of catching exceptions, such as NoSuchElementException or a NumberFormatException (a parsing module), would only catch RuntimeException and print out a msg which in its entirety was "Error". Very very bad code that and had to bug him to make the error messages a bit more descriptive, I mean during the prototyping phase at least print out the Class.Method()
 
Status
Not open for further replies.