Exceptions in apex class constructor
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.Stri开发者_开发技巧ngException se ){
..
}
catch( System.NullPointerException ne ){
..
}
catch( Exception e ){
..
}
....
}
Agreed with @mmix.
Following operation can never result in any exception.
ApexPages.currentPage().getParameters().get('myParam');
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.
There is nothing to catch here
currentPage()
is not null if inside controller/extension
getParameters()
is not null even if parameter list is empty
get('myParam')
may or may not return null, but regardless that value gets stored in myVar
only 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.
精彩评论