Questions tagged [try-catch]

try-catch is used to catch the exception.

Filter by
Sorted by
Tagged with
71
votes
5answers
9k views

Pokemon Catch - Generic Exception Handling In Apex

I read a great post about this topic on Stack Overflow: Is it really that bad to catch a general exception? However, I asked this question on our exchange because I am interested in a more specific ...
16
votes
5answers
6k views

When do we really need try/catch?

I know about 'always in DML operations'. But for what? What do we get? The code will crash anyway, and we can find the error in logs even without this construction. What's the main point of try/catch? ...
14
votes
3answers
6k views

Can I throw an exception in apex and still log the caught exception?

I'm really wrestling with the best error handling strategy. My goal is to handle all exceptions that I can identify, log them to a table in the database, and surface a helpful message about what ...
10
votes
2answers
2k views

What is an elegant way to catch multiple exceptions without catching generic exceptions?

I don't want to catch generic exceptions, but I want to handle all the exceptions I want to catch exactly the same way. For arguments sake, lets say the code is: try { doSomething(); } catch(...
10
votes
1answer
4k views

Catch System.AssertException

Is there a way to catch System.AssertException? For example, some class is known to throw assertions in certain cases and it's ok to deal with that on some upper level. But unfortunately ...
9
votes
4answers
851 views

Using try, catch and finally in test class (dreamhouseapp)

In the test classes of the DreamHouse Sample app all the functions have the following structure: static testMethod void testSomething() { Boolean success = true; try { ... } catch (...
9
votes
1answer
683 views

Handing REST API POST Exceptions using SSJS Try-Catch on a Landing Page Form Submission with AMPSCRIPT

I have an issue with a landing page containing a webform that submits input from the user and using AMPSCRIPT I make a Rest API call using the HTTPPost2 function to utilize the validateEmail resource. ...
8
votes
1answer
4k views

Catch Regex too complicated when splitting a string in salesforce

I have created a function wherein I split a string from the csv filecsvAsString.split('\n') . It is working when the string is not so big. But when I try to split a very large string, an error will ...
5
votes
2answers
7k views

Handling exception using custom exception

I have an custom exception , just an example to see how I can write my own exception class and what could be the purpose of the exception. public class AccountException extends Exception { ...
5
votes
2answers
529 views

Custom Logging, @Future, Transaction Control

I have a similar question to these two: Custom Logging and Future Methods Custom Exception Handling & Logging But my question this time is: can I put the @Future annotation on the Logger Class? ...
5
votes
1answer
984 views

Exceptions and DML

It was to my understanding that when you throw an exception all previous operations are rolled back. When an exception occurs, code execution halts and any DML operations that were processed ...
5
votes
1answer
984 views

do javascript remoting calls need a try/catch?

Currently in my javascript remoting calls I check for if (event.status===true) in the callback. I handle any errors in an else. However, it seems it also throws an exception. Example: [Error] ...
4
votes
1answer
2k views

Cant catch exception and log to custom object if I throw exception

Background: I have worked w/ a consultant to build an Apex rest endpoint, and its working well. Now I am adding some basic error handling, by putting the insert / update statements into try/catch ...
4
votes
1answer
3k views

Custom Exception Handling & Logging

I've set out to build a custom error handling and logging feature for my org wherein all apex exceptions will be logged into a custom sObject for analysis and follow-up. public class TriggerException ...
4
votes
0answers
44 views

Is this a good Model for “Guaranteeing” Record Updates Don't Fail due to ROW_LOCK/Race Conditions?

Background: The zqu__Quote__c object in our org has two child objects from another managed package we use for eSignature and credit card capture. One of those two child objects collects the Credit ...
3
votes
4answers
535 views

Untyped Catch Block?

Is it possible to have an empty catch block in Apex? I have the following code for illustration. COMPILES: public with sharing class Demo_ApexCatchBLock { public Date SendmeData(String input) ...
3
votes
1answer
703 views

Overriding Standard error message in VF Page

For a currency field (say 10,2) , Salesforce displays a standard error message below the field as Error: Number is too large. My requirement would be to display an apex page message instead. I ...
3
votes
1answer
321 views

Is it Possible to Catch an Unknown Exception?

I am creating a button that will allow System Admins to reset user passwords via System.resetPassword. We have password restrictions setup such that a password must exist for 24 hours. Therefore, if ...
3
votes
2answers
250 views

Resource is inserted even thought it has a conflicting schedule with another event

I am using standard Public Calendars and Resources where I have 2 types of resources, Vector Unit and Demo Unit. Now if any of the resources have a conflicting schedule, a standard Salesforce error is ...
3
votes
1answer
121 views

DMLException handling in a Before trigger context?

I got 99% of the way through refactoring a trigger from "after" to "before" when I noticed one little thing I'd overlooked when judging whether or not to do it: My trigger copies data from "holding ...
3
votes
1answer
135 views

Rewriting Try + Catch{System.Assert(false, 'blahblah')} for easy toggle-off of catch?

Dear Salesforce StackExchange, An outside partner set a precedent in some of our Apex triggers of doing major operations (such as DML) inside a try/catch block, and having the catch block simply ...
3
votes
1answer
1k views

SFMC SSJS error handling - try catch

I have the following code: <script runat="server"> Platform.Load("Core","1.1.1"); try{ var logDE = DataExtension.Init("testDE"); throw "this is an error"; logDE.Rows.Add({"c1":"...
3
votes
0answers
38 views

Best approach to handling Post-Install script exception

As inspired by this post on when to use try catch blocks, if we have a post-install script for our managed package, what's the best approach to gracefully catching and handling an exception? It ...
2
votes
2answers
786 views

Salesforce - soql System.QueryException Try Catch Issues

I am building dynamic soql query from an object. I am getting the object in a Field and another field from a object in Salesforce for the Query. With that said I am trying to capture the Query ...
2
votes
1answer
60 views

Try Catch Only Reading First Line

I am writing a try catch in my constructor but can not get past the first query of crs. Is there a limit on how many queries you can do in a try catch? What would the reason be for not allowing the ...
2
votes
3answers
121 views

Coverage for Catch Block (cant generate exception in try{}) give another solution

NOTE : This question is not duplicate.Please go through code once. Here is the situation - I am calling this method from my test class, and here My_obj__c records are getting created and added in ...
2
votes
1answer
50 views

Can't catch exception from ChatterFeeds

I have this code. It still generates an error despite of my catching statement: (max length=5000) I can't catch this error! This is my method and how to i catch exception from it: void ...
1
vote
2answers
364 views

Exception not being caught; System.FinalException: Cannot modify a collection while it is being iterated

Why is this Exception not being caught? I read that System.LimitException is not caught but didn't see anywhere about System.FinalException. Non-Working Code @AuraEnabled public static List<...
1
vote
3answers
138 views

How to cover Catch block in ApexUnitTest class when using DML statement in try body

I have some apex code, where I try to upsert a list of records: try { upsert recordList Accounts; } catch (DmlException e) { //do a loooot of stuff in order to provide a proper ...
1
vote
2answers
756 views

Test Class for Bounced Email (try/catch coverage)

I'm trying to write a test class to cover the try/catch section in the following code but am unsure how to test for the error. I only have 69% code coverage w/o it. Or is there a way in the test ...
1
vote
1answer
114 views

try and catch with a count

If this statement has no records will it return 0 or does the "try" feature cause it to fail and fall thru to the "catch" statement after an if/else statement. The "if" statement checks for the ...
1
vote
1answer
4k views

How to do code coverage for Catch Block:

Below is my apex class: public void submitForApproval(List<Account> acc) { try{ for(SObject ac :acc) { if((ac.Account_Record_Type_Name__c == 'A' || ac....
1
vote
0answers
234 views

Will this work? Apex utility method to catch exceptions on DML statements [closed]

So I am realizing that I should really put try/catch blocks around all the DML statements in my after triggers, but then I realized that maybe I can just write up a dynamic utility method that ...
1
vote
2answers
281 views

batch class Run fine with individual record but not working fine with multiple records

I am writing batch class to deactivate users if no dependency and freeze user if any dependency.When i hardcode singal value of userid and run batch it works fine it deactivates user.It is not going ...
1
vote
0answers
1k views

Unable to cover Clone() method in test class

I'm having a simple code where I'm cloning an opportunity object with the necessary child elements. When I'm writing a test class for it, the clone method is not called and it is going into catch ...
0
votes
2answers
93 views

Why catch code of an try catch exception are not executed when System.LimitException: Too many DML statements: 151

I have the next code block that generates a limitException: Account myAccount = new Account(Name = 'MyAccount'); Insert myAccount; For (Integer x = 0; x < 150; x++) {Account newAccount = new ...
0
votes
2answers
374 views

Governor Limit Exception and Finally blocks

We all know that if you hit a Governor Limit Exception, your code/application will terminate with an unhandleable exception know as a Governor Limit Exception. My question is does your code ...
0
votes
2answers
1k views

Try/Catch in for loop

I am trying to grab a list of unique users from a subset of leads and I am running into a System.QueryException: List has no rows for assignment to SObject error. Here is my new code below. If I get ...
0
votes
1answer
33 views

How to cover the catch block for after insert Trigger?

When you create a Barrel, a Filling is also created. Is there any chance to make a fake error in unit test between Barrel and Filling to crush the upsert process and cover the catch block? Helper: ...
0
votes
1answer
240 views

Multiple DML operation in the same try and catch block

I wanted to ask if there a problem doing upsert and delete in the same try-catch block, or maybe it better to separate them. for example : try { Schema.SObjectField oCode = Opportunity.Fields....
0
votes
3answers
1k views

How to write a try catch for Rest Api

How do I catch an error if the insert goes wrong in my rest API or is this not needed since I get an API respone? @HttpPost global static ID createInvoice ( String customerId, ...
0
votes
3answers
740 views

how to cover code for catch block?

public class QMT_ReviewSubmit { public static QMT_Apex_Debug_Logs__c logger = new QMT_Apex_Debug_Logs__c(Apex_Class__c = 'QMT_ReviewSubmit', Type__c = 'UI'); public static String QMTThumbnail = ...
0
votes
2answers
424 views

Try Catch blocks within a Custom Controller?

I have a VF page which is fired based on a custom button click from Case record's detail page. window.location = 'apex/onClickPage?Id={!Case.Id}'; In Apex controller class, I am getting the Id from ...
0
votes
1answer
591 views

Need help getting value to refresh in LWC without refreshing browser

I have an apex class that passes in the value of 'lastCallSource' to do a SOQL query on a Custom MetaData Type that will display a custom field value from the metaData to the user. I have this working,...
0
votes
2answers
107 views

Catch block code coverage for @HttpPost and @HttpGet REST API

I have some code in my catch block for both @Post and @Get methods. I need to cover catch block to get to 75% for GET, got catch block covered for POST Here is an example : // POST my JSON : [ ...
0
votes
1answer
582 views

Test Code coverage to Cover Catch Block

My Apex Class where I'm having a validation rule for duplicate name check in Catch block public pagereference save(){ try{ upsert complexity; pg = new ApexPages....
0
votes
3answers
2k views

Not able to catch exception using try catch block

I am using try-catch block to catch exceptions.code is executing inside try block.Exceptions happens which i am thinking i am handling in catch block.When i debug whole code after exception code is ...
0
votes
1answer
93 views

How to advoid Maximum view state size limit (170KB) exceeded. Actual view state size for this page was 292.001KB

I currently have an apex class which creates an object record and attaches 2 files. I added a loop to be able to have the option to add more attachments based on counter. I currently have some ...
0
votes
1answer
30 views

Start fresh after error handling message

So I have a validation rule that doesn't allow a user to enter in a "Receiving Quantity" that is greater than the "Open Quantity" custom field. If I have an open quantity of 5, but I enter in 6 as the ...
0
votes
1answer
297 views

Why is SSJS Platform.Function.ParseJSON not going into catch block if JSON has bad format

I expect this code going into catch block because "hello" is no valid json. But this is not the case. Do you have any idea? <script runat="server"> Platform.Load("core","1.1.1"); var ...