views:

446

answers:

4
  1. What happens when an exception is thrown and you I have try-finally structure (without catch)

  2. What does this do?

.

public class Bicycle{

  private int cadence;
  private int gear;
  private int speed;

  // the part with static:????
  static{           
    something // I don't remember exactly the format     
  }            
  // the part with static:????
}
A: 
  1. If you have a try-finally block without a catch, this just means you aren't trying to catch any specific exceptions. This means that whenever try is exited, the code within finally will be executed (it doesn't matter how you got to it).

  2. I think you're just asking what static means? static basically means you're defining a member or method that doesn't need to be associated with an instance of a class to work. Static variables are in contrast to instance variables, which require an instance of a class (they are unique to a specific instance, whereas static variables are the same for the entire class). More on the static keyword is here.

Josh Leitzel
+5  A: 

1: Whatever is inside the finally block will always be executed, regardless of whether the code throws an exception or not. It's often used to clean up resources such as closing files or connections. Without a catch clause, any thrown exception in your try block will abort execution, jump to your finally block and run that code, then let the thrown exception propagate upwards to the calling method. That is, a finally clause is not a replacement for a catch clause.

2: static initializers contain code that will run when that class is loaded by the JVM. I believe a class is loaded the first time one of its methods/fields/constructors are referenced (not necesssarily invoked) by another class. Static initializers look like this:

static {
System.out.println("Class loaded");
}

After coding Java for 10 years I've never had any need for them so I wouldn't worry about them.

Martin
+1 - though you should mention in 1) that the exception will not be caught.
Stephen C
A: 
  1. That means your exception won't be handled when there is an exception thrown inside the try block. Finally block will always be executed right after the try block is finished, whether an exception was thrown or not.

  2. That is the static initialization block. Static variables that is inside this block will be initialized when the class is first loaded. It only runs once when the class is first loaded.

jpartogi
You don't DECLARE static variables inside a static initializer.
Stephen C
A: 
  1. also have a look at the Java Language Specification Execution of try-catch-finally (just assume that the Exception is not being catched by the catch statement)

  2. same source: Static Initializers (not more than what already have been posted here)

Carlos Heuberger