官术网_书友最值得收藏!

Embracing an exception

The Exception class includes various methods that help you better understand why an exception was thrown. You can even find out the type of exception, what line of Apex code caused the exception, and even get the entire stack trace. In addition to the built-in exception types, Apex includes the ability to create your own exception types. This allows you to catch a system exception, evaluate it, and throw your own custom exception. Although it involves slightly more work, a custom exception type can be the difference between frantically debugging code in the middle of the night and sleeping like a baby. Imagine writing code to integrate with an outside system. There are times where that process will fail (like when the other system is under maintenance). If you proactively throw your own exception, you'll immediately know why it failed. The following code will show you how to define a custom exception type:

//Define our custom Exception type
Public class myCustomException extends Exception{}

//Try calling out to our outside system
try {
httpRequest req = new httpRequest();
//You have to whitelist the endpoint in Setup|Remote Site Settings
req.setEndpoint('http://www.madeUpUrl.net');
req.setMethod('GET');
//Set the timeout to 1 millisecond to force an exception
req.setTimeout(1);
httpResponse res = new http().send(req);
} catch ( Exception e){
if (e.getTypeName() == 'System.CalloutException' && e.getMessage() == 'Read timed out'){
  throw new myCustomException('Go Back to Sleep', e);
} else {
  throw e;
}
}
主站蜘蛛池模板: 邯郸市| 巢湖市| 孟连| 永和县| 三门县| 南通市| 汤阴县| 民权县| 仙居县| 科技| 襄汾县| 伊宁县| 达孜县| 涡阳县| 临漳县| 河源市| 康平县| 罗城| 澄迈县| 太原市| 庆城县| 泰顺县| 腾冲县| 聊城市| 红河县| 瑞安市| 罗定市| 沽源县| 阿勒泰市| 临沂市| 孝感市| 昭通市| 盐津县| 丰县| 寿光市| 惠来县| 江门市| 札达县| 丰原市| 拉萨市| 达州市|