Purpose of Finally keyword?

hi i just read this http://www.roseindia.net/help/java/e/finally-keyword.shtml but i still don't quite get the purpose or use
of the finally keyword if it's executed no matter if the exception is thrown or not? like wat's the difference between just having a catch statement and code afterwards, and having using finally with the same code?
thanks,
newbie

saru88 wrote:
hi i just read this http://www.roseindia.net/help/java/e/finally-keyword.shtml but i still don't quite get the purpose or use
That's probably because roseindia is a pretty bad site filled with half-truths, misinformed advice and straight out errors.
Read [the official tutorial|http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html] instead.
of the finally keyword if it's executed no matter if the exception is thrown or not?Yes.
like wat's the difference between just having a catch statement and code afterwards, and having using finally with the same code?You can get almost the same effect as the finally block using this technique (almost, because you can't execute code after a "return;" this way, for example).
It is harder however.
Another important advantage of finally is that it is also executed when you don't catch the exception yourself (for example because you want it thrown further or you didn't expect that exception to happen).
Finally is used for cleanup that needs to run, no matter if your try-block successfully completes or not.

Similar Messages

  • Use of final keyword on methods arguements ?

    Hi All,
    Just say I have an input arguement for a method which is an int. If I wanted to access the value stored by the input arguement reference inside an anonymous class that is contained in the method one way would be to pass the input arguement reference to a instance variable of the class that contains the method and use that.
    // Declared at start of  class
    int arrayIndex = 0;
    methodName(nt inputNumber)
        arrayIndex = inputNumber;
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[arrayIndex] = 100;
    }Just wondering, I used the final keyword on the the input arguement instead and then used the input arguement directly instead. It seemed to work ok. Is this good programming practice or are there some pitfalls to using this that I'm not aware of?
    (I don't need to change what the input arguement reference points to)
    // Alternate
    methodName(final int inputNumber)
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[inputNumber)] = 100;
    }Regards.

    declaring it final guarantees that you will not change the value.Of course it does. That's what it's for. That's what it means. But you're only guaranteeing that to yourself. It doesn't form part of the interface contract so it's no use to anybody else. Which is the bigger picture.
    Whenever i use any anonymous classes i prefer to use the final variables as long as i dont need to change their values.No you don't 'prefer' it, you are forced to do that by the compiler.

  • Shoukd the 'final' keyword should be used on all input parameters?

    In my very limited experience as a java programmer have never seen this done any where. Except in the java.lang.Math class which has a final variable, of type double, called PI. As pi is not a value that should change during the execution of a program, though this is not passed in as a parameter.
    However, on a new project, a co-worker is proposing the use of the 'final' keyword on all input parameters as a standard. He has about 5 years experience of maintaining java systems and is putting this suggestion forward as in the past people have overwritten values passed in as parameters causing confusion. Personally I don't see why this is such a major issue if one reads the code of the called programs.
    I would be grateful if anyone has seen this done before, or has any views on the advantages or disadvantages of this.
    Thanks in advance,
    LS

    Lord_Sidcup wrote:
    In my very limited experience as a java programmer have never seen this done any where. Except in the java.lang.Math class which has a final variable, of type double, called PI. As pi is not a value that should change during the execution of a program, though this is not passed in as a parameter.
    I'm sorry, but this point is irrelevant. There are lots of final fields (but not that many final parameters) in Java, BTW. Every field you declare in an interface is automatically final, for example.
    However, on a new project, a co-worker is proposing the use of the 'final' keyword on all input parameters as a standard. He has about 5 years experience of maintaining java systems and is putting this suggestion forward as in the past people have overwritten values passed in as parameters causing confusion. Personally I don't see why this is such a major issue if one reads the code of the called programs.
    IMHO, it's definately not a major issue. It is simply being restrictive, to be restrictive. The guy may have "five years experience", but he sounds lazy, to me. Besides, the first thing I would do in that case (if final were the default), would be something like this:
    public void myMethod (final String a, final int b) {
      String myA = a;
      String myB = b;
    }And now, what has he won by making it final? It simply added some up front work for some people, with no real added value. Also, if I had to retroactively change my code, I would change it as follows:
    //Original Code
    public void myMethod (String myA, int myB) {
      String myA = a;
      String myB = b;
    // New code
    public void myMethod (final String a, final int b) {
      String myA = a;
      String myB = b;
    }That way, you wouldn't even have to worry about changing anything else about your method, as the variables actually used in the rest of the body will remain the same.
    I would be grateful if anyone has seen this done before, or has any views on the advantages or disadvantages of this.The only thing declaring the parameter final does, is it prevents you from assigning a new value to the variable. The instance that parameter references (as long as it is not immutable to begin with) can still be manipulated. I.E. except in some very narrow, and specific, cases, no value added, simply a restriction that exists to be restrictive.
    >
    Thanks in advance,
    LSEdit: And man, am I slow and long-winded.

  • Help needed understanding final keyword and  use 3

    Hi Everyone,
    I have been studying a book on multi-threading and have inadvertently come accross some code that I don't really understand. I am wondering if anybody can explain to me the following:
    1). What effect does using the final keyword have when instantiating objects, and
    2). How is it possible to instantiate an object from an interface?
    public class BothInMethod extends Object
         private String objID;
         public BothInMethod(String objID)
              this.objID = objID;
         public void doStuff(int val)
              print("entering doStuff()");
              int num = val * 2 + objID.length();
              print("in doStuff() - local variable num=" + num);
              // slow things down to make observations
              try{
                   Thread.sleep(2000);
              }catch(InterruptedException x){}
              print("leaving doStuff()");
         public void print(String msg)
              String threadName = Thread.currentThread().getName();
              System.out.println(threadName + ": " + msg);
         public static void main(String[] args)
              final BothInMethod bim = new BothInMethod("obj1");  //Use of final on objects?
              Runnable runA = new Runnable()      //Creating objects from an interface?
                   public void run()
                        bim.doStuff(3);
              Thread threadA = new Thread(runA, "threadA");
              threadA.start();
              try{
                   Thread.sleep(200);
              }catch(InterruptedException x){}
              Runnable runB = new Runnable()
                   public void run()
                        bim.doStuff(7);
              Thread threadB = new Thread(runB, "threadB");
              threadB.start();
    }If you know of any good tutorials that explain this (preferably URL's) then please let me know. Thanks heaps for your help.
    Regards
    Davo

    final BothInMethod bim = new BothInMethod("obj1");  //Use of final on objects?
    Runnable runA = new Runnable()      //Creating objects from an interface?          
         public void run()               
                                    bim.doStuff(3);               
    };Here final is the characteristics of bim reference variable and it is not the characteristics of class BothInMethod
    This means u cannot use bim to point to some other object of the same class
    i.e, u cannot do this
                       final BothInMethod bim = new BothInMethod("obj1"); 
                       bim  =  new   BothInMethod("obj2");  This bim is a constant reference variable which will point only to the object which it is initialized to
    and not to any other object of the same class later on.
    How is it possible to instantiate an object from an interface?Regarding this yes we cannot create an object from an interface but
    but here it is not an interface u are providing the implementation of the interface Runnable
    as
    new Runnable()
    }This now no longer stays an interface but now it is an object that implements the interface Runnable

  • Related with Final Keyword...

    Hi,
    I written the following code to iterate over an array :
    for(final int i:arr)
    System.out.println(i);
    }

    jschell wrote:
    I really doubt that the compiler doesn't erase the final part.
    It is a compile time rather than run time check.Runtime as well, it seems.
    public class Final {
      public static final int i = 999;
    public class FinalChanger {
      public static void main(String[] args) {
        Final.i = 123;
        System.out.println(Final.i);
    }1) Compile both without the final keyword in Final.java
    2) Put final into Final.java, and recompile.
    3) Run javac -cp . FinalChanger
    Exception in thread "main" java.lang.IllegalAccessError
            at FinalChanger.main(FinalChanger.java:3)
    :; javap -s -c -verbose -classpath . Final
    Compiled from "Final.java"
    public class Final extends java.lang.Object
      SourceFile: "Final.java"
      minor version: 0
      major version: 50
      Constant pool:
    const #1 = Method       #3.#14; //  java/lang/Object."<init>":()V
    const #2 = class        #15;    //  Final
    const #3 = class        #16;    //  java/lang/Object
    const #4 = Asciz        i;
    const #5 = Asciz        I;
    const #6 = Asciz        ConstantValue;
    const #7 = int  999;
    const #8 = Asciz        <init>;
    const #9 = Asciz        ()V;
    const #10 = Asciz       Code;
    const #11 = Asciz       LineNumberTable;
    const #12 = Asciz       SourceFile;
    const #13 = Asciz       Final.java;
    const #14 = NameAndType #8:#9;//  "<init>":()V
    const #15 = Asciz       Final;
    const #16 = Asciz       java/lang/Object;
    public static final int i;
      Signature: I
      Constant value: int 999
    public Final();
      Signature: ()V
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    :; javac -version
    javac 1.6.0_06
    :; java -version
    java version "1.6.0_06"
    Java(TM) SE Runtime Environment (build 1.6.0_06-b02)
    Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode)

  • Static and final keyword questions

    Brief summary: I want to make the JButtons, JLabels, and JPanels public static final. Is that bad, and why? And what the heck is the Java system doing when it compiles and runs a program that does this? Is the code more efficient?
    More questions below.....
    I'm new to making GUI designs with Java. I am going to school and my teacher is making us do GUI interfaces in JAVA.
    Early on, I learned that constants are identifiers similar to variables except that they holda particular value for the duration of their existence. QUESTION ONE: what happens during run-time, how does JAVA handle this constant?
    I also learned that some methods may be invariant, as with a simple extension. These methods should be marked final. The subclass inherits both a madatory interface and a mandatory implementation. So I guess you use a final method when you want to model to a stric subtype relatinoship between two classes. All methods not marked final are fair game for re-implementation.
    Well, that's good and well. So then I started thinking about static. That's a keyword in Java and when used with a variable, it's shared among all instances of a class. There is only one copy of a static variable for all objects of a class. So then again, I noticed that the programs in my book that used final usually threw in the word static before it. Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
    Well, that too is great? Question 2: In my GUI programs, can I declare all the buttons (JButtons), labels (JLabels), panels (JPanels) as being final constant static?
    In the program I don't intend to change the type of button, or JPanel so why not make it a constant? As long as I'm doing it, why not make it static? WHAT IS ACTUALLY GOING ON THEN IN MY PROGRAM WHEN I DO THIS?
    Question 3: What goes on in JAVA when I make a method or function public static final. Is that what the Math class does? How is that handled during run-time? Is the code faster? Is it more efficient?
    Question 4: If I make a class final, that means a subclass cannot extend it? Or does it mean that a subclasss cannot change it? I know that if the function or method in the parent class was final, then the subclass inherits both a madatory interface and a mandatory implementation....So if the class is final, then what?

    You have a lot of questions..
    You make a method final if it should not be allowed for subclasses to override it.
    If you make a class final, you will not be able to subclass that class.
    A static method is a class method, i.e. you don't need to create an instance of the class to call the method.
    You can make any object and primitive final, but for objects, you are still able to modify what is inside the object (if there is anything you can and are allowed to modify), you just can't change the final reference to point to another object.
    When you make a variable final, you sometimes make them static as well if they should work like constants. Because there is no reason that every instance of the class has their own copy of constants.
    If you make everything static, why even bother to work with object-oriented programming. It gives you no reason to make instances of your classes. You should try not to make static variables and methods when there is no need for it. Just because you start from a static main method, it doesn't mean it is necessary to make all variables and methods static.
    Don't think so much about performance issues as long as you are still learning java. When you make a method final, it is possible for a compiler to inline that method from where you call the method, but you will hardly gain much in performance with that. In most cases it's better to optimize the code you have created yourself, e.g. look at the code you run inside loops and see if you can optimize that.

  • Why does final keyword work differently with collection

    I have tried final on StringBuffer but when i changed the value of StringBuffer object its throws a compile time error but when i did same thing with vector it work perfectly fine.
    any one knows the reason? please send me in details.
    final Vector v = new Vector();
    v.add("String1");
    v.add("String2");
    final StringBuffer sb  = new StringBuffer();
    sb = sb.append("xyz");

    Because you haven't understood the keyword final. when you make a reference final you may not change the object to which it points to.
    final StringBuffer sb  = new StringBuffer();This is valid because this is the first time you instatiate sb
    sb = sb.append("xyz");this is invalid because you are trying to assign a new object to a reference that may only be assigned to once.
    Compare
    final int testInt = 1;
    testInt = 2; //errorthe vector works because you do not assign vector reference v a new Vector object

  • Final keyword

    Say you have a variable that you want to be able to instantiate once, and only once. In other words, you want to instantiate this variable during the initialization of your class, and from that point on, you don't want anything to be able to change it.
    So, is there any way of accomplishing what this code WOULD be attempting to do?...
    final String s;
    public myConstructor(String str)
    this.s = str;
    myMethod();
    void myMethod()
    System.out.println(s);
    s = "abc"; // throws exception
    Notice that the variable would need to be an instance object that is accessible to all scopes within the class. So, I can't just do...
    void myConstructor(String str)
    final String s = str;
    myMethod();
    }

    My only intent, for the time being, is to understand
    if it is possible to have a final variable, which is
    assigned it's value from a parameter passed into the
    object's constructor. And, have that variable within
    the class scope, so that all other methods in that
    object can access the variable directly.Yes, that is possible. The code you posted originally already does that..! If you didn't try to reassign the variable in a method, it would compile fine and do exactly what you have stated you are after.
    From what I'm hearing, it's doesn't sound like there
    is any way to do that in Java, right?Perhaps you really have a different set of requirements to what you are stating. Can you tell us concisely what you actually want to achieve? - don't get hung up on whether the variable is final or not - if you perhaps really want to do something like initialise a variable once and once only, but from anywhere in the class rather than being forced to do it in the constructor, then there might be a design pattern that fits the bill for you, but that doesn't necessarily have anything to do with final variables. I doubt you'll getting a good answer to this question without a better explaination of what you actually want to achieve (and perhaps why?).

  • Final keyword and return type ...

    static byte m1() {
    final char c = 'b';
    return c; // THIS IS FINE NO COMPILER ERROR
    static byte m2() {
    char c = 'b';
    return c; // COMPILER ERROR
    The first return type is LEGAL, but the secoond type is not because it is not final. Why is this the case? Going from a char to a byte is a down conversion. Why does the compiler allow it for a final variable and dis-allow it for the other variable?

    i am curious... what is this one about ?See section 5.2 of the JLS, regarding assignment conversion:
    Assignment conversion occurs when the value of an expression is assigned (�15.26) to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of an identity conversion (�5.1.1), a widening primitive conversion (�5.1.2), or a widening reference conversion (�5.1.4). In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:
    The expression is a constant expression of type byte, short, char or int.
    The type of the variable is byte, short, or char.
    The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

  • About final keyword

    hai plz help me,
    why the final methods are not allowing overriding?

    Well, that's the easy answer; if you put final on a method declaration you're saying "this method cannot be overriden."
    Why would you want to do that?
    Security reasons - you might want to prevent an implementer from changing some kind of security checking method, for example.
    Optimisation. When compiling a call to a final method the compiler may be able to determine exactly which method is to be called (early binding). With a non-final instance method the actual method to be called can be determined only at run time (late binding). So final may result in a slightly faster call.

  • Question  about Abstract,Final Class

    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private. From usability perspective both are same ? or is there any difference?
    Secondly accounting to java syntax a class can be either final or abstract and not both .Then why language specification doesn't impose any restriction on making abstract classes constructor private. We can create an Abstract class with private Constructor (Basically utility class with all methods are static) ,to make this class Singleton .This situation is equal to abstract final class ?
    Thanks,
    Paul.

    EJP wrote:
    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private.No it doesn't.
    Secondly accounting to java syntax a class can be either final or abstract and not both.Correct.
    Then why language specification doesn't impose any restriction on making abstract classes constructor private.Why should it? That proposition doesn't follow from your previous sentence.I think OP is asking about this case
    public abstract class WTF {
      private WTF() {}
      private WTF(...) {}
    }where the class is abstract and all the c'tors are final. It's an abstract class that cannot be extended, much like a final abstract class would be if it were allowed. So, since purpose of abstract classes is to be extended, the OP seems to be asking, "Why can we, in this fashion, create an abstract class that cannot be extended?"
    I don't know the answer to that, but I would guess that, while final is an explicit syntactical element for the purpose of making a class non-extensible, in the all-private-c'tors case, the non-extensibility is simply a side effect, and probably enough of a corner case that it wasn't worth the effort to explicitly forbid it in the spec.
    I also think it's something not worth thinking much about. It was certainly not a key point of some grand design.

  • Invoice posting possible for limit PO although final invoice is set

    Hi,
    I encountered a strange behavior, I think.
    I created a limit PO and posted several invoices against it. So far, so good.
    Then, I wanted to "close" the limit PO and set the "Final invoice" indicator in PO. Even though, I was able to post further invoices against this PO. Shouldn't this be prevented?
    I used the workaround to modify the PO and change the expected value to the actual value of invoices posted against the PO... But why does final invoice flag have no effect at all? Any ideas?
    Thanks in advance!

    Hi,
    The purpose of final invoice indicator is to reset the purchase order commitments. The final invoice indicator does not prevent further invoices from being posted.  Please see F1 help documentation on this field.
    You can block the item if further processing is required.
    Kind Regards,
    Suneet

  • Why are keywords for Delicious bookmarks no longer recognized in Firefox 25 and Firefox 26?

    I use Delicious Bookmarks 2.3.4 for synchronizing bookmarks and their keywords on different computers. After updating to Firefox 25 the keywords are no longer recognized. If I enter a keyword like "foo" it doesn't send me to the bookmark with the keyword but starts a google search for "foo". When I downgrade to Firefox 24 it works again.
    Was this change introduced by purpose (like the keyword search removal in FF 23) or is this only some side effect?
    Is there any way to get rid of this problem and have that feature again?

    That would be a question for Delicious support or Help.
    Have you tried some basic Firefox troubleshooting, like the Firefox SafeMode? <br />
    https://support.mozilla.org/en-US/kb/troubleshoot-firefox-issues-using-safe-mode
    Firefox 25 was released 6 1/2 weeks ago and this is the first mention I have seen in this forum about Delicious keywords no longer working in Firefox 25 and above.

  • Adding/Deleting keywords for multiple images

    Well, I'm finally paying the price for bad keyword management and I'm trying to clean up my nightmare of a system now but running into trouble.
    I'm using Lightroom 3.2.
    My workflow follows one of two types:
    1) I'm shooting something specific (soccer games) and I import the shots and immediately assign the appropriate keywords (soccer, which kid it is, which tournament it is)
    2) I've taken shots of multiple events/subjects and I haven't had time to download and organize.  I will then import with a 'file later' tag so I can easily search and keyword them later and then re-use the card.
    Well 'file later' is now about 3000 images!  Doh!
    I'm going through and properly assigning them but I'm having a lot of trouble with what I *think* should work in Lightroom.
    There are several things here:
    First, if I choose the 'File Later' keyword, it will pull up the metadata filters options on the top of the grid view.  No matter what I do, I can't make it go away.  If I do get it to go away, I wind up viewing ALL my pictures which is not what I want.
    Second, if I choose multiple pictures by ctrl-clicking or shift-clicking, It appears I can assign a keyword to multiple shots.  I cannot REMOVE a keyword from multiple shots. Lightroom seems to only want to remove the keyword from one picture at a time even if they are all selected.
    Third, the painter tool does not work...at all.  Enabling it and then selecting and applying or removing does nothing.
    So, what am I looking for here? 
    Organizing for these should be pretty easy since most are in blocks and I can apply the same keywords quickly.  However, removing the keywords one at a time is a huge pain. 
    What am I doing wrong?
    Thanks

    First, if I choose the 'File Later' keyword, it will pull up the metadata filters options on the top of the grid view.  No matter what I do, I can't make it go away.  If I do get it to go away, I wind up viewing ALL my pictures which is not what I want.
    This is the filter dialog - of course if you close it you turn back to All Photographs. Try creating a Smart Collection based on your File Later keyword - this collection will automatically populate all your images that have that particular keyword. Once you have keyworded the pictures from e.g. one particular shot, just remove the File Later-KW and those images will disappear from the collection.
    Second, if I choose multiple pictures by ctrl-clicking or shift-clicking, It appears I can assign a keyword to multiple shots.  I cannot REMOVE a keyword from multiple shots. Lightroom seems to only want to remove the keyword from one picture at a time even if they are all selected.
    I'm not sure why you can't remove keywords from multiple images - it just works fine here by selecting multiple images and delete the keyword.
    Most of the times I use the Keyword List to assign/delete keywords because in my opinion it is the easiest way - I just browse thru my list or filter for a particular kw and tick the box on the left.
    Creating a hierarchical keyword list can further simplify your work. For example the location: organize the final keyword xyz-Soccer Stadium into other keywords like Town>County>State>Country>Continent>Places, then you only have to tick the last keyword xyz-Soccer Stadium and with that assign all of those keywords in the hierarchy (I know thats kind of a complicated explanation...but I suggest you play around a bit and then you will get the full picture ).

  • Final Invoice tick in PO

    What is the use and purpose of Final Invoice tick in PO  ?

    During IV posting, this indicator can be set maually at invoice item. Please see note  377304.
    Solution
    In contrast to the delivery completed. indicator, the final invoice
    indicator is not set automatically for purchase order or invoice
    documents: it can only be set manually.
    Create the invoice after entering the invoice amount and the purchasing
    document, setting the final invoice indicator manually in the invoice
    item. In the standard system, an entry is possible at this point.
    Logistics invoice verification:
    Post the invoice and then go to the invoice document display or direct
    to the display screen for the relevant purchase order. The final invoice
    indicator should now be set in both cases.
    Conventional invoice verification:
    The indicator is not adopted in the invoice document when the latter is
    saved. Here it only serves to set the final invoice indicator in the
    purchase order.
    Use:
    The final invoice indicator serves as information for the applications -
    cash management and forecast
        o  Cash budget management
        o  Funds management
        o  IS-PS (Industry Solution - Public Sector)
    If you set the final invoice indicator, purchase order commitments are
    reset. However, the final invoice indicator does not prevent the posting
    of further invoices. Neither does it replace GR/IR account maintenance
    in the event of a variance between the quantity of goods received and
    the invoice quantity. It has no influence on the reorganization of
      purchase orders.
    Kind Regards,
    Suneet

Maybe you are looking for

  • PF Calculation for Employee Joined After 15th of the month.

    Hi All, I have an issue with the PF calculation where the system is calculating the period the person worked in the month not the full period while running his payroll in the next month. Exmp: Basic Salary 10000, PF- 12%=1200 Emp Joined on 18th of ap

  • End user training material

    Hi Friends, i am looking for end user training material for A/R,A/P and CIN. if anybody have that please porvide me with the same. My Mail ID is [email protected] Thanks in Advance RK

  • Background and space issues in IE

    A coworker has designed a site. The page looks great in all browsers except IE. In IE the background behind the text shows up white. It should have a textured background like the rest of the page. There is also some spacing issues with the graphics.

  • Hierarchies in Analysis Authorizations

    Hi - I have a role based Anlaysis Authorization created for access to all infoareas in BI. This information is put in the AA in the hierarchy. But one inforarea was not included and I need to add it to the existing list. We are unable to report on  t

  • Special Procurement using External Procurement & Subcontracting

    Hello everyone! We currently have a material  that is set up as "F" Procurement Type (External) with Special Procurement Type "30" (Subcontracting). We have active scheduling agreements for subcontracting procurement of this material.  User also need