Java: how to access destinations in try-catch -loop?

The problem leads me to big try-catch loops. I want less. So how to access assignments in loops?

$ javac TestInit2.java 
TestInit2.java:13: variable unknown might not have been initialized
  System.out.println(unknown);
                     ^
1 error

the code

import java.util.*;
import java.io.*;

public class TestInit2 {

 public static void main(String[] args){
  String unknown;
  try{
   unknown="cannot see me, why?";
  }catch(Exception e){
   e.printStackTrace();
  }
  System.out.println(unknown);
 }
}
+3
source share
5 answers

The compiler stops you from doing something, which is most likely an error, since after your try-catch block you probably assume that the variable is initialized. However, if an exception is thrown, it will not be initialized.

- . , , , , .

, , , , :

    String unknown = null;
    try{
        unknown="cannot see me, why?";
    }catch(Exception e){
        e.printStackTrace();
    }
    System.out.println(unknown);

- , , :

    String unknown;
    try{
        unknown="cannot see me, why?";
    }catch(Exception e){
        e.printStackTrace();
        unknown = "exception caught";
    }
    System.out.println(unknown);        

, , , catch, , . :

    String unknown;
    try{
        unknown="cannot see me, why?";
    }catch(Exception e){
        e.printStackTrace();
        //return; // if you just want to give up with this method, but not bother breaking the flow of the caller
        throw new Exception("Uh-oh...", e); // if you want to be sure the caller knows something went wrong
    }
    System.out.println(unknown);   
+4

unknown ( null, , ):

import java.util.*;
import java.io.*;

public class TestInit2 {

    public static void main(String[] args){
        String unknown = null;
        try{
            unknown="cannot see me, why?";
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println(unknown);
    }
}

try, , unknown - , , .

+9

, . , , , . , :

String unknown = null;

, , println - .

+3

unknown , , null. , try, , - . , , unknown , println() .

EDIT: , , try, , , , .

+2

. , println, , , .

+1
source

Source: https://habr.com/ru/post/1740966/


All Articles