“catch (Exception NullPointerException)”与”catch (NullPointerException e)”写法相同吗?

huangapple go评论67阅读模式
英文:

Is "catch (Exception NullPointerException)" the same as writing "catch (NullPointerException e)"?

问题

我最近在一个作业中加入了一个简单的try catch语句,并且我将它写成了以下形式:

try { ... }
catch (Exception NullPointerException) { ... }

这样写在功能上是否与以下方式相同:

try { ... }
catch (NullPointerException e) { ... }

在我测试时,代码运行得很好,但我想确保我正确理解了catch语句的工作方式。这两种格式都是可行的吗?

英文:

I recently included a simple try catch statement in an assignment, and I wrote it as follows

try { ... }
catch (Exception NullPointerException) { ... }

Is this functionally the same as writing:

try { ... }
catch (NullPointerException e) { ... }

The code ran fine when I tested it, but I wanted to make sure I am grasping the way catch statements work correctly. Are both these formats viable?

答案1

得分: 2

首先,

第一个块表明它能够处理任何类型的异常。

try{//此处为代码}
catch(Exception NullPointerException){//此处为代码}

而第二个块表明它只能处理NullPointerException类型的异常。

try{//此处为代码}
catch(NullPointerException e){//此处为代码}

其次,

第一个块中的*NullPointerException*与第二个块中的*e*没有区别。它们最终都是引用变量。可以重命名或更改为任何随机名称。它的行为始终是相同的。

英文:

Firstly,

The first block indicates that it is capable to handle any type of exception.

try{//code here}
catch(Exception NullPointerException){//code here}

While the second block indicates that it can handle only NullPointerException type of exception.

try{//code here}
catch(NullPointerException e){//code here}

Secondly,

There is no difference between *NullPointerException* in first block and *e* in second block. They are ultimately reference variables. It can be renamed or changed to any random name. It's behavior would be always same.

答案2

得分: 1

这总是

    捕获(异常类 异常变量名)

其含义是“捕获类型为异常类或其派生类的异常,并将其赋值给变量异常变量名”。

在您的示例中,第一种情况中的catch(Exception NullPointerException)中,Exception是类名,NullPointerException是非常规的变量名。

第二种情况中的catch(NullPointerException e)
NullPointerException是异常类,e是变量名。

英文:

Its always

catch (ExceptionClass exceptionVariableName)

which says "catch exceptions of type ExceptionClass or its descendants and assign it to a variable exceptionVariableName

In your examples, in first case catch(Exception NullPointerException) Exception is the class and NullPointerException is non conventional variable name.

Second case catch(NullPointerException e)
NullPointerException is an exception class and e is a variable name.

huangapple
  • 本文由 发表于 2020年9月15日 03:14:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63890566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定