I'm learning the APEX world (coming from the .NET world).
Defined a custom exception.
In a method (say A()) i'm using a try catch block in which, i 'm calling another method of another class (say Classname2.B() ).
In this Classname2.B() i 'm throwing the public defined Exception.
This does not get caught!!
If instead i throw the exception in the try catch block, then the exception gets caught! What do i miss? Shouldn't this work also in APEX (like in the .NET world)?
public class SomeClass {
public void A() {
try {
//...
Classname.B(); //<- doesn't work
throw new CustomException();//<-works
//...
}
catch(CustomException ex) {}
}
}
public class Classname {
//...
void B() {
//....
throw new CustomException();
//...
}
}
EDIT: Here is the actual code (which is stripped down to only the relevant parts).
The trigger looks like this:
trigger Expenses on Expense__c (before insert, before update) {
if(Trigger.isBefore && (Trigger.isUpdate || Trigger.isInsert)) {
Travel__c travel = getTravel();
ExpensesTriggerHandler.onBeforeInsertOrUpdate(trigger.new, travel);
}
}
The ExpensesTriggerHandler looks like this:
public with sharing class ExpensesTriggerHandler {
public static void onBeforeInsertOrUpdate(List<Expense__c> newExpenses, Travel__c travel) {
ExpenseValidator.validate(newExpenses, travel);
}
}
The ExpenseValidator looks like this:
public with sharing class ExpenseValidator {
private static List<ExpenseRule> rules;
static {
rules = new List<ExpenseRule>();
for(ApexClass clazz : [SELECT NamespacePrefix, Name FROM ApexClass WHERE isValid = true]) {
Type t = Type.forName(clazz.NamespacePrefix, clazz.Name);
try {
ExpenseRule rule = (ExpenseRule) t.newInstance();
rules.add(rule);
}
catch(Exception ignored) {}
}
}
public static void validate(List<Expense__c> expenses, Travel__c travel) {
for(ExpenseRule rule : rules) {
for(Expense__c expense : expenses) {
rule.validate(expense);
}
}
}
}
One of the classes implementing the ExpenseRule Interface is the following (from which the exception gets thrown):
public with sharing class ExpenseCannotEndBeforeStartRule implements ExpenseRule {
private final static String ERROR_MESSAGE = 'Expense begins after end.';
public void validate(Expense__c expense) {
if (expense.dtm_DepartureTime__c > expense.dtm_ArrivalTime__c){
throw new ExpenseValidationException(ERROR_MESSAGE);
}
}
}