function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ranu Jain SFDCRanu Jain SFDC 

try-catch block covering complte code of method

Hii All,
I have a query that should we apply try - catch block in complete method ciovering all lines or only for those that generate exceptions like DML statements.
my concern that what we want that our functionalty should not break any where , in case any exception occurs (any kind) it should be in message format. But issue is it will create problem in test classes as trst classes also nit fails due to exception handling and it will be difficult to find out for test coverage.

please let me know your thoughts.
pconpcon
To test this, you'll want to throw an unhandled exception and then set it up to be thrown for a test.

Class example
global with sharing class MyAPI {
	public static Boolean THROW_EXCEPTION = false;
	public class UnhandledException extends Exception {}

	public static void generateExceptionForTesting() {
		if (Test.isRunningTest() && THROW_EXCEPTION) { 
			throw new UnhandledException('Exception for testing');
		}
	}

	public static String ERR_MSG = 'OH NOES!';

	WebService static String myWebservice(Integer i) {
		String result = i;

		try {
			generateExceptionForTesting();
			MyOtherClass.somePotentiallyDangerousMethod(i);
		} catch (Exception e) {
			result = ERR_MSG;
		}

		return result;
	}
}

Test example

static testMethod void negativeTest() {
	Integer i = 0;

	Test.startTest();

	MyAPI.THROW_EXCEPTION = true;
	String result = MyAPI.myWebservice(i);

	Test.stopTest();

	System.assertEquals(MyAPI.ERR_MSG, result, 'Wrong result');
}

More information: http://pcon.github.io/presentations/testing/#exceptional-unknown-class-pre