The local variable may not have been initialized - Detect thrown exception exception within the method

I have code with this structure:

public void method() { Object o; try { o = new Object(); } catch (Exception e) { //Processing, several lines throw new Error(); //Our own unchecked exception } doSomething(o); } 

I have several methods in which I have the same code in a catch block, so I want to extract it into a method to save some lines. My problem is that if I do this, I get a compiler error "Local variable o may not be initialized."

 public void method() { Object o; try { o = new Object(); } catch (Exception e) { handleError(); } //doSomething(o); compiler error } private void handleError() throws Error { //Processing, several lines throw new Error(); } 

Is there any workaround?

+7
java exception compiler-errors unchecked
source share
5 answers

You need to initialize local variables before they are used below

 public void method() { Object o=null; try { o = new Object(); } catch (Exception e) { handleError(); } doSomething(o); } 

You will not get a compilation error until you use a local variable that has not been initialized

+5
source share

Since o initialized inside a try block, and o initialization can throw an exception, java believes that the doSomething(o) statement can reach without o to be initialized. Therefore, java wants o be initialized. Incase new Object() throws an exception.

So, initializing o with null fixes the problem

 public void method() { Object o = null; try { o = new Object(); //--> If new Object() throws exception then o remains uninitialized } catch (Exception e) { handleError(); } if(o != null) doSomething(o); } 
+3
source share

Initialize your object: Object o = null; but watch out for the NullPointerException that can be thrown when you pass it to method calls.

+3
source share

Just put doSomething(o) inside the try { } block:

 public void method() { Object o; try { o = new Object(); doSomething(o); } catch (Exception e) { handleError(); } } 

You may not want to do doSomething () if the creation of your object failed!

+2
source share

An instance variable is an object type, so you must initialize to null

 public void method() { Object o=null; try { o = new Object(); } catch (Exception e) { handleError(); } doSomething(o); } 
0
source share

All Articles