为什么这不是有效的Java?

Blu*_*ell 0 java optimization coding-style code-snippets

当然这应该是有效的Java?我的语法有些错误吗?

return (url != null) ? url : (throw new NotFoundException("No url"));
Run Code Online (Sandbox Code Playgroud)

如果不是,我想我必须这样做:

if(url == null)
    throw new NotFoundException("No url");
return url;
Run Code Online (Sandbox Code Playgroud)

谁有更简洁的东西?

Lui*_*oza 5

因为你没有完成回报:

return <comparison> ? <value1> :(else) <value2>
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你正在实现value1但不是value2,而是你正在抛出一个新的例外.

您的实际第一个代码将被翻译为

if (url != null) {
    return url;
} else {
    return throw new NotFoundException("No url"); //makes sense?
}
Run Code Online (Sandbox Code Playgroud)

  • @Blundell - `?:`结构不是if/else语句. (2认同)