在使用三元运算符为什么我不能抛出一个异常 [英] Why can't I throw an exception while using the ternary operator

查看:746
本文介绍了在使用三元运算符为什么我不能抛出一个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不会编译,并给出以下错误:前pression 的非法启动。为什么呢?

 公共静态的AppConfig的getInstance(){
        返回mConfig!= NULL? mConfig:(抛出新的RuntimeException(错误));
    }


解决方案

这是因为在Java三元操作符的形式为前pression?前pression:前pression ,以及你给一份声明中作为最后一部分。这没有意义,因为声明没有给出一个值,而前pressions做。什么是Java的意思时,发现病情是假的,并试图给出第二个值呢?有没有价值。

三元运算符的设计,让您可以迅速做出两个变量之间的选择,而无需使用完整的如果语句 - 这是不是你正在尝试做的,所以不要使用它,最好的解决办法很简单:

 公共静态的AppConfig的getInstance(){
    如果(mConfig!= NULL){
        返回mConfig;
    }其他{
        抛出新的RuntimeException(错误);
    }
}

This doesn't compile and gives the following error : Illegal start of expression. Why?

public static AppConfig getInstance() {
        return mConfig != null ? mConfig : (throw new RuntimeException("error"));
    }

解决方案

This is because a ternary operator in java takes the form expression ? expression : expression, and you are giving a statement as the final part. This doesn't make sense as a statement doesn't give a value, while expressions do. What is Java meant to do when it finds the condition to be false and tries to give the second value? There is no value.

The ternary operator is designed to allow you to quickly make a choice between two variables without using a full if statement - that isn't what you are trying to do, so don't use it, the best solution is simply:

public static AppConfig getInstance() {
    if (mConfig != null) {
        return mConfig;
    } else {
        throw new RuntimeException("error");
    }
}

这篇关于在使用三元运算符为什么我不能抛出一个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆