apex 类构造函数中的异常
我一直在尝试捕获 Salesforce 自定义 apex 类中的异常,但似乎不起作用。
在本例中,我有一个初始化环境的控制器构造函数,我试图捕获构造函数中的异常,但不起作用,异常未被捕获。
public MyController(){
try{
this.myVar = ApexPages.currentPage().getParameters().get('myParam');
....
}
catch( System.StringException se ){
..
}
catch( System.NullPointerException ne ){
..
}
catch( Exception e ){
..
}
....
}
I've been trying to catch an exception in a Salesforce custom apex class but doesn't seems to work.
In this case I have a controller constructor that initializes the environment and I am trying to catch exceptions in the constructor, but doesn't work, the exception is not catched.
public MyController(){
try{
this.myVar = ApexPages.currentPage().getParameters().get('myParam');
....
}
catch( System.StringException se ){
..
}
catch( System.NullPointerException ne ){
..
}
catch( Exception e ){
..
}
....
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
同意@mmix。
以下操作永远不会导致任何异常。
事实上,捕获 NPE(NullPointerException) 是一种不好的做法,因为这些是运行时异常,应该检查变量 != null 或变量 == null 而不是依赖于 NPE 异常。如果您使用这样的 try catch 块,代码流将很难维护和理解。
Agreed with @mmix.
Following operation can never result in any exception.
In fact catching NPE(NullPointerException) is bad practice, as these are runtime exceptions and one should check for a variable != null OR variable == null instead of depending on NPE exceptions. Code flow will be too hard to maintain and understand if you use try catch blocks like this.
这里也没有什么可捕获的
如果控制器/扩展内部的
getParameters()
不为空,即使参数列表为空,currentPage()
不为空get('myParam ')
可能返回 null,也可能不返回 null,但无论该值是否存储在 myVar 中,只有当您稍后尝试引用 myVar 的实例成员时,您才会得到
System.NullPointerException
,即使存储 null数据库中的 myVar 有效。There is nothing to catch here
currentPage()
is not null if inside controller/extensiongetParameters()
is not null even if parameter list is emptyget('myParam')
may or may not return null, but regardless that value gets stored in myVaronly if you were to later try and reference myVar's instance members will you get
System.NullPointerException
, even storing null myVar in database is valid.