简体   繁体   English

Java:如何在try-catch -loop中访问作业?

[英]Java: how to access assignments in try-catch -loop?

The problem drives me to the big try-catch loops. 这个问题让我陷入了巨大的try-catch循环。 I want smaller. 我想要更小。 So how to access assignments in the loops? 那么如何在循环中访问赋值?

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

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);
 }
}

You need to assign an initial value to unknown (in this case I have used null but feel free to assign any value that makes sense for your application): 您需要将一个初始值分配给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);
    }
}

Since your assignment occurs inside a try the compiler has no way of verifying that unknown will ever be assigned a value so it is possible that you could use the variable without an assigned value. 由于您的分配中发生try编译器无法验证的方式unknown永远不会被分配一个值,因此它是可能的,你可以使用这个变量没有分配的值。

The compiler is stopping you from doing something that is most likely a mistake, since after your try-catch block, you would probably assume that the variable is initialized. 编译器阻止你做一些很可能是错误的事情,因为在你的try-catch块之后,你可能会假设变量被初始化了。 If an exception is thrown, however, it will not be initialized. 但是,如果抛出异常,则不会初始化它。

You will need to assign the variable to something before using it. 在使用变量之前,您需要将变量赋值给它。 It is, however, possible to just assign it to null, if you want it to be null if the assignment fails. 但是,如果要在赋值失败时将其指定为null,则可以将其指定为null。

So, if you want the variable to be null if the assignment fails, try this: 因此,如果您希望变量在赋值失败时为null,请尝试以下操作:

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

If you want to set the variable to something else if an exception is caught, try this: 如果要在捕获异常时将变量设置为其他内容,请尝试以下操作:

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

Also, if it doesn't make sense to proceed with the execution of your method if the assignment fails, you might want to consider either returning from the catch block, or throwing another exception which would be caught by the caller. 此外,如果在分配失败的情况下继续执行方法没有意义,则可能需要考虑从catch块返回,或者抛出另一个将由调用者捕获的异常。 For example: 例如:

    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);   

You are "trying" to set that variable's value, which wasn't initialized. 您正在“尝试”设置该变量的值,该值未初始化。 That means that if an exception was caught when trying to do that assignment, the assignment wouldn't have happened and the variable would remain uninitialized. 这意味着如果在尝试执行该分配时捕获到异常,则分配将不会发生,并且变量将保持未初始化状态。 To get rid of the error, declare the variable like: 要摆脱错误,请将变量声明为:

String unknown = null;

That way, at the very least, println will be able to resolve something. 这样,至少,println将能够解决问题。

You never give unknown a value when you declare it, not even null . 在声明它时,你永远不会给出一个unknown值,甚至不是null The compiler doesn't know what happens in the try block, and can't guarantee that anything inside takes place. 编译器不知道try块中发生了什么,并且不能保证内部发生任何事情。 So, as far as it knows, unknown isn't referencing anything until the moment your println() hits. 所以,据他所知,在你的println()命中之前, unknown不会引用任何东西。

EDIT: To clarify, all the compiler knows is that an exception might be thrown at any point during a try block, so it can't assume that what you put in there will succeed. 编辑:澄清一下,所有编译器都知道在try块期间的任何时候都可能抛出异常,所以它不能假设你放在那里的东西会成功。

The key word in the compiler message is might . 编译器消息中的关键字可能是 It doesn't mean it's not possible for the variable to be initialized when the variable is accessed in the println call, just that there is a possibility that it would not be, hence the compiler complains. 这并不意味着当在println调用中访问变量时,不可能初始化变量,只是有可能它不会,因此编译器会抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM