This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

A small error relating with return  RSS feed

 
midhun raj
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...
 
Matthew Brown
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!