Click here to Skip to main content
15,891,921 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Java
public static void main (String args[] )
{
    int a ;
    try 
    {
        a=4 ;
    }
    finally {
    }
    System.out.println (a ) ;
}


Why this does not give a compile time error when finally is used ? I am not able to understand the logic behind this . I have understood the case when we use catch instead of finally and it gives a compile time error . But why not here ?

What I have tried:

I have run this on Netbeans IDE .
Posted
Updated 25-Apr-17 6:39am
v3
Comments
[no name] 25-Apr-17 11:57am    
"Why this does not give a compile time error", why do you think it should?
"I am not able to understand the logic", why not? It's been explained to you already.
Maybe you should start learning how to do research yourself instead of asking the same question over and over and over
https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Richard MacCutchan 25-Apr-17 12:32pm    
Because the expression a=4 will not throw an exception, so it will always be set in the finally clause.
Richard MacCutchan 25-Apr-17 12:34pm    
See how much easier it is to read when the code is formatted properly, and the text is left in normal font.

1 solution

Think about it: what is a try...catch block meant to do?
It catches exceptions, and diverts execution directly to the catch block code.
So if your code looks like this:
C#
int a ;
try 
   {
   a=4 ;
   }
catch (Exception ex)
   {
   Console.WriteLine(ex.Message);
   }
Then the system can "see" an execution path where a is not initialised: when a problem occurs in the assignment. It's not likely to happen in your example, but it very much could in a more complex case:
C#
int a ;
try 
   {
   a=GetValue();
   }
catch (Exception ex)
   {
   ...
   }
If an exception occurs in GetValue, the value of a is never set.
Using finally is different: it doesn't catch an exception, so either the assignment will be executed or the code after the try...finally block will not (as the exception isn't handled, it it dealt with by a higher level method once the finally code is complete).

This is very much the same problem you had yesterday: Why the variable x has to be initialized when using inputstreamreader class ?[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900