• 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
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

A small error relating with return

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To print the bytes in a file
...

i get the error...



if i modify this program...


it works fine what does return got to do inside catch.. please help me thanks in advance...
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about what happens if an Exception is thrown when you create the FileInputStream. In this case, nothing is assigned to fin, and so fin is still uninitialized (since you didn't give it an initial value on line 7).

Now, in your first example, you catch the error, print a message....and carry on. You then try and read from fin, which still hasn't been initialized. The compiler won't let this happen - it won't let you do anything with fin unless it knows it will definitely have a value.

In the second case, when the exception is caught you exit the method straight away with your return statement. So you can't reach the line where you read from fin without it being initialized - if there was an error you skip it completely. So the compiler is happy.
 
midhun raj
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

When using return i am getting output like this...
But if its return works with catch then how come the rest of the main program gets executed to give this output..
Will not the program terminate at the return point..

Thanks for your help and support...
I am very much new to java program ..
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the program will be terminated...but only if an exception is thrown. That's what the catch block is for - it is only run if an exception is thrown in the try block.

So if there's a problem opening the file - for example, if the file doesn't exist or you don't have the right permissions - the program will end. But if it opens correctly, then the program continues.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic