Skip to content
Advertisement

Initializing variable in try catch block

I am getting the error in Java:

Exception in thread “main” java.lang.Error: Unresolved compilation problem
The local variable b1 may not have been initialized at Test.main(Test.java:20)

Here is my code:

JavaScript

Advertisement

Answer

The problem here is that getBytes(String encoding) throws UnsupportedEncodingException. If such an exception occurs in your code (this will happen if you put wrong encoding for example getBytes("foo")), your byte array will remain uninitialized. The catch block will handle the exception and continue with the for loop where you are trying to use b1. The compiler sees that possibility and throws an error in order to prevent usage of uninitialized variable later.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement