简体   繁体   English

如果已抛出RunTimeException并且未捕获,则返回类型值

[英]Return type value if RunTimeException has been thrown and not catched

I am using Gson to parse Json. 我正在使用Gson解析Json。 What I don't understand what the return type will be if you don't catch the Runtime Exception . 我不明白,如果您没有捕获Runtime Exception ,返回类型将是什么。 I was expecting it to be null , but it is not null when evaluating with a simple if statement. 我期望它为null ,但是使用简单的if语句求null时它不会为null

My code looks something like this: 我的代码如下所示:

public X x(final String jsonString) {
   return gson.fromJson(jsonString, X.class);
}

then from another function I call the function: 然后从另一个函数调用该函数:

public void y() {
  final X x = x();
  if (x == null) {
    System.out.println("x == null");
  }
}

I was expecting x to be null, but it isn't because the print statement is not called? 我期望x为空,但这不是因为未调用print语句吗? What is the value of x ? x的值是多少? I have solved my problem by using a catch block in the x() function and returning null from inside the catch block. 我已经通过在x()函数中使用catch块并从catch块内部返回null来解决了我的问题。 But I am just wondering what the value of function x() is(if any?)? 但是我只是想知道函数x()的值是多少(如果有的话?)? Hopefully I make any sense at all. 希望我完全没有道理。

If x() is throwing an exception, the x variable remains uninitialized, since the control flow was interrupted. 如果x()引发异常,则由于控制流已中断,因此x变量将保持未初始化状态。 Without a try/catch, the exception keeps going up the stack and x is never usable. 如果没有try / catch,则异常会不断上升,并且x永远无法使用。 With a try/catch, x is only valid within the block, so if an exception happens it won't be usable. 使用try / catch时, x仅在块内有效,因此,如果发生异常,将无法使用。

If you try to do something like: 如果您尝试执行以下操作:

X x;
try {
    x = x();
} catch(RuntimeException e) {}
if (x == null) {
    ...

you'll get the error "variable x might not have been initialized", since control flow can bypass the assignment 您将收到错误“变量x可能尚未初始化”,因为控制流可以绕过分配

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

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