10.3 TryCatch, Retry Scope & Custom Exception Architectures

Key Takeaways

  • Try Catch runs the Try block, then the most specific matching Catch, and always runs Finally.

  • The Try Catch activity chooses the most specific matching Catch regardless of list order, but listing specific types before System.Exception keeps the workflow readable.

  • Rethrow, which is allowed only inside a Catch, preserves the original exception and stack trace, while Throw raises a new or reset exception.

  • Custom exception classes belong in C# code source files or referenced libraries; deriving from BusinessRuleException keeps REFramework's business path working.

  • Retry Scope runs its Action and Condition up to NumberOfRetries times (default 3, counting the first attempt) with a RetryInterval pause (default 5 seconds).

Last updated: September 2026

10.3 TryCatch, Retry Scope & Custom Exception Architectures

Core Concept: Building enterprise-grade, resilient automations requires a structured, multi-layered exception handling architecture. UiPath Studio provides robust language-level and framework-level constructs—chief among them the TryCatch container, the lightweight Retry Scope, and the ability to define strongly typed Custom Exceptions. Mastering the precise execution mechanics of these tools, maintaining stack trace integrity via Throw vs. Rethrow, and enforcing strict catch block inheritance hierarchies prevents unhandled faults from corrupting business data and ensures rapid, auditable incident remediation.

In unattended automation environments, software robots operate without direct human supervision. When an ERP interface experiences latency, a database connection drops, or a business document violates processing guidelines, the automation must detect, categorize, isolate, and respond to the fault deterministically. Relying on default unhandled behavior results in orphaned system sessions, corrupted transactional records, and inflated mean-time-to-resolution (MTTR).


1. The TryCatch Activity: Architecture & Execution Mechanics

The TryCatch activity is the fundamental building block of defensive programming in UiPath Studio. Modeled on Microsoft .NET structured exception handling, it encapsulates failure-prone logic and routes execution through dedicated recovery pathways.

+--------------------------------------------------------------------------------+
|                              TRYCATCH CONTAINER                                |
|                                                                                |
|  +--------------------------------------------------------------------------+  |
|  | TRY BLOCK: Primary execution sequence containing risk-prone activities.  |  |
|  | - Read Transaction Data from Remote API                                  |  |
|  | - Write Transaction Record to SQL Database                               |  |
|  +--------------------------------------------------------------------------+  |
|                                       │                                        |
|                     (If an exception occurs during Try)                        |
|                                       ▼                                        |
|  +--------------------------------------------------------------------------+  |
|  | CATCHES: Typed handlers; the most specific matching type runs.          |  |
|  | - Catch [BusinessRuleException]: Log validation fault & notify user      |  |
|  | - Catch [System.Data.SqlClient.SqlException]: Log DB fault & rollback   |  |
|  | - Catch [System.Exception]: Universal fallback for unhandled technical   |  |
|  +--------------------------------------------------------------------------+  |
|                                       │                                        |
|                          (Executes unconditionally)                            |
|                                       ▼                                        |
|  +--------------------------------------------------------------------------+  |
|  | FINALLY BLOCK: Resource cleanup and state finalization.                   |  |
|  | - Close SQL Database Connection & Release File Locks                      |  |
|  +--------------------------------------------------------------------------+  |
+--------------------------------------------------------------------------------+

The Tripartite Architecture

  1. Try Block: Houses the primary workflow activities intended for normal execution. If all activities within the Try block complete successfully, execution skips all Catches handlers and proceeds directly to the Finally block. The moment any activity in Try throws an exception, execution immediately halts within Try and transfers to Catches.
  2. Catches Block: A collection of one or more typed exception handlers. When an exception occurs, the activity chooses the Catch whose type matches the thrown exception exactly, or else the most specific type the exception inherits from. That Catch runs its recovery logic (e.g., logging errors, setting status variables, performing rollback routines).
  3. Finally Block: Contains cleanup and finalization logic that executes unconditionally upon exiting the TryCatch construct. The Finally block executes under all possible exit scenarios:
    • When the Try block completes with zero errors.
    • When an exception occurs in Try and is caught and handled by a Catch block.
    • When a Catch block executes a Rethrow or Throw activity.
    • Even when an unhandled exception escapes a Catch block, Finally executes before the exception bubbles up to parent scopes.
    • Enterprise Use Case: Closing active file streams, disposing of database connections, resetting temporary environment variables, or releasing application semaphores.

.NET Exception Inheritance & The Order of Catches

All exceptions in UiPath Studio derive from the base .NET class System.Exception. Understanding this class hierarchy is paramount when configuring multiple Catch handlers:

.NET Exception Inheritance Hierarchy in UiPath
System.Object
└── System.Exception (Universal Base Class)
    ├── UiPath.Core.BusinessRuleException (Domain Validation Errors)
    └── System.SystemException (Technical & Operating System Errors)
        ├── System.IO.IOException
        │   ├── System.IO.FileNotFoundException
        │   └── System.IO.DirectoryNotFoundException
        ├── System.Net.WebException (Network & HTTP Faults)
        ├── System.Data.Common.DbException (Database Connection Faults)
        └── System.NullReferenceException (Uninitialized Variable Faults)

How the Try Catch Activity Picks a Catch

UiPath's Try Catch activity comes from Windows Workflow Foundation. When an exception is thrown, it looks for the Catch whose exception type matches the thrown type exactly, and otherwise for the most specific Catch type that the exception inherits from. UiPath's own tutorial puts it this way: the Catches always match the most specific exception first, even when a generic System.Exception Catch is also present.

  • Order does not decide the winner. A System.IO.FileNotFoundException is handled by a FileNotFoundException Catch even if a System.Exception Catch appears above it in the list.
  • Still list them from specific to general. Readers of the workflow expect that order, and it matches how you would write the code in C# or VB.NET, where the order of catch clauses does matter.
  • Typical list:
    1. Catch [UiPath.Core.BusinessRuleException] (domain business rule violations)
    2. Catch [System.IO.FileNotFoundException] (a specific missing file)
    3. Catch [System.IO.IOException] (broader disk errors)
    4. Catch [System.Exception] (the fallback for anything else)

2. Stack Trace Integrity: Throw vs. Rethrow

In enterprise production environments, rapid incident diagnosis depends on the clarity of exception logs. The UiPath workflow runtime records an exception's origin via its StackTrace, which captures the chronological call hierarchy, workflow filenames, container activities, and exact line numbers where the fault originated.

+--------------------------------------------------------------------------------+
|                      THROW VS. RETHROW EXECUTION DYNAMICS                      |
|                                                                                |
|  Scenario: Error occurs in Workflow 'SubmitInvoice.xaml' at Activity 'Click'   |
|                                                                                |
|  Approach A: Throw ex (ANTI-PATTERN)                                           |
|  [Catch ex] ──► [Throw ex]                                                     |
|  * STACK TRACE DESTROYED: Stack trace resets to the 'Throw' activity inside   |
|    the Catch block. Diagnostic visibility into 'SubmitInvoice.xaml' is lost!   |
|                                                                                |
|  Approach B: Rethrow (ENTERPRISE STANDARD)                                     |
|  [Catch ex] ──► [Rethrow]                                                      |
|  * STACK TRACE PRESERVED: Preserves the original failure site in               |
|    'SubmitInvoice.xaml' at Activity 'Click', including inner exceptions!       |
+--------------------------------------------------------------------------------+

The Throw Activity

  • Operational Mechanics: Instantiates and raises a brand-new exception object into the execution pipeline.
  • Stack Trace Reset: Executing a Throw activity sets the exception's originating StackTrace to the location of the Throw activity itself.
  • Primary Use Cases:
    1. Raising a BusinessRuleException when a data validation rule is breached (e.g., Throw New BusinessRuleException("Invoice total cannot be negative.")).
    2. Translating a low-level technical exception into a domain-specific custom exception.
  • Critical Anti-Pattern (Throw ex): A frequent mistake made by novice developers is catching an exception variable ex inside a Catch block and then executing a Throw activity with Value = ex. This practice wipes out the original stack trace and resets the error origin to the Catch block itself, blinding support teams to the true root-cause activity.

The Rethrow Activity

  • Operational Mechanics: Re-elevates the exact existing exception currently being handled within a Catch block, propagating it upward to the calling workflow.
  • Scope Constraint: The Rethrow activity can only be placed inside a Catch block of a TryCatch activity. Placing it anywhere else produces a validation error in Studio.
  • Stack Trace Preservation: Unlike Throw, Rethrow leaves the original exception object, its inner exceptions, and its entire call stack completely intact.
  • Enterprise Role: Essential when a sub-workflow needs to perform local remediation or logging (such as taking a diagnostic screenshot or logging a local warning) before allowing the calling parent workflow (such as REFramework's Process.xaml) to handle the transaction-level failure.

3. Creating Custom Exception Architectures

While standard .NET and UiPath exceptions cover technical system faults and basic business rule failures, complex enterprise processes benefit significantly from Strongly Typed Custom Exceptions.

Why Define Custom Exceptions?

  • Semantic Clarity: Differentiating between distinct business failure modes (e.g., VendorValidationException, CreditLimitExceededException, DuplicateInvoiceException) rather than relying on generic string parsing of exception messages.
  • Granular Catch Handling: Workflows can declare dedicated Catch blocks for specific business conditions, applying tailored recovery logic (such as routing a transaction to a specialized human review queue in Action Center) without capturing unrelated business exceptions.

Implementing Custom Exceptions in UiPath

Custom exception classes can be implemented in a C# code source file inside the project or in an external class library referenced as a package. Invoke Code bodies cannot declare classes.

// Enterprise Custom Exception in C# (Coded Workflow / Class Library)
using System;
using UiPath.Core;

[Serializable]
public class VendorValidationException : BusinessRuleException
{
    public string VendorTaxID { get; }
    public decimal InvoiceAmount { get; }

    // Standard constructor
    public VendorValidationException(string message) : base(message) { }

    // Enriched diagnostic constructor
    public VendorValidationException(string vendorTaxId, decimal amount, string message) 
        : base($"Vendor Validation Failed for Tax ID '{vendorTaxId}' (Amount: {amount:C}): {message}")
    {
        this.VendorTaxID = vendorTaxId;
        this.InvoiceAmount = amount;
    }
}
' Custom exception in a referenced VB.NET class library
<Serializable>
Public Class DatabaseTimeoutException
    Inherits System.Exception

    Public Property TargetDatabase As String

    Public Sub New(dbName As String, message As String, inner As System.Exception)
        MyBase.New($"Database operation timed out on '{dbName}': {message}", inner)
        Me.TargetDatabase = dbName
    End Sub
End Class

4. The Retry Scope Activity: Transient Fault Resilience

While TryCatch provides full control over exception handling, using it to implement retry loops introduces substantial visual clutter and maintenance overhead (requiring variables for loop counters, retry delays, and exit flags). The Retry Scope activity encapsulates this pattern into a lightweight, high-performance container.

+-------------------------------------------------------------------------------+
|                             RETRY SCOPE CONTAINER                             |
|  NumberOfRetries: 3 | RetryInterval: 00:00:05 | ContinueOnError: False        |
|                                                                               |
|  +-------------------------------------------------------------------------+  |
|  | ACTION BLOCK: Logic to execute and retry upon failure.                  |  |
|  | - Click 'Download Monthly Report' Button                                |  |
|  +-------------------------------------------------------------------------+  |
|                                       │                                        |
|                                       ▼                                        |
|  +-------------------------------------------------------------------------+  |
|  | CONDITION BLOCK: Validation activity returning Boolean or UI State.     |  |
|  | - File Exists 'C:\Reports\MonthlyReport.pdf'                            |  |
|  +-------------------------------------------------------------------------+  |
+-------------------------------------------------------------------------------+

Execution Lifecycle of Retry Scope

The Retry Scope consists of two distinct functional compartments:

  1. Action Block: Contains the sequence of activities that perform the target operation.
  2. Condition Block: Contains an activity that validates whether the action achieved its desired outcome. The activity placed in this block must either return a Boolean variable or implement condition verification (e.g., Element Exists, Check App State, File Exists).

Operational Rules & Evaluation Flow

  1. Action Execution: The runtime executes the Action sequence.
  2. Condition Evaluation: If the Action completes without throwing an exception:
    • The runtime evaluates the Condition block.
    • If the Condition evaluates to True (or if no Condition is specified and Action completed without errors), the Retry Scope exits successfully.
  3. Retry Trigger: If the Condition evaluates to False, OR if an unhandled exception is thrown anywhere inside the Action or Condition blocks:
    • The runtime catches the failure internally.
    • It pauses execution for the duration specified in the RetryInterval property.
    • It increments the internal retry attempt counter.
    • It re-executes the Action block from the beginning.
  4. Exhaustion & Fault Propagation: If the configured NumberOfRetries attempts are used up without success, the Retry Scope throws an exception, unless Continue On Error is set to True. The first attempt counts toward the number, so the default of 3 means at most three executions of the Action.

Key Configuration Properties

  • NumberOfRetries (Int32): The number of attempts (default 3). UiPath's own example sets it to 3 and describes that as attempting the action three times.
  • RetryInterval (TimeSpan): The pause between attempts; the default is 5 seconds. Lengthen it when the system you are waiting on needs more time to recover.
  • ContinueOnError (Boolean): If set to True, suppresses the final failure exception when retries are exhausted, allowing parent workflows to proceed. Default is False.

5. Enterprise Defensive Architecture & Fault Tolerance Comparison

Enterprise robotic automations integrate multiple layers of defense to establish self-healing capabilities:

Multi-Layered Enterprise Fault Tolerance Architecture
Level 1: Transient UI / Network Layer ──► Retry Scope (Atomic In-Place Retries)
Level 2: Transaction Boundary Layer   ──► REFramework TryCatch (Process.xaml)
Level 3: Global Safety Net Layer      ──► Global Exception Handler (GlobalHandler.xaml)
Level 4: Orchestrator Queue Layer     ──► Queue Auto Retry (Max # of retries)

Architectural Comparison Table

Feature / DimensionTryCatchRetry ScopeGlobal Exception HandlerREFramework Queue Retry
Operational ScopeActivity block or transaction scopeAtomic UI / network operationEntire automation projectEntire transaction item
Interception MethodCatches exceptions explicitly by typeCatches any error or unsatisfied conditionRuns for activity errors in the call stack and returns an ErrorActionCatches exceptions escaping Process.xaml
Retry GranularityManual (requires custom looping logic)In-place atomic retry of Action blockIn-place retry of failed activityFull transaction retry from Init state
Condition CheckingBased on exception type matchingExplicit Condition activity verificationEvaluates errorInfo.RetryCount & metadataEvaluates in_TransactionNumber & retry limits
Application State RecoveryCustom recovery logic in Catch/FinallyNone (assumes transient glitch)None (retries activity in current state)Restarts all target applications cleanly
Primary Enterprise RoleTransaction boundaries, resource disposalPolling file creation, transient UI clicksEmergency project safety net & loggingResilient, distributed transaction processing
Loading diagram...
Try Catch execution flow and Catch selection
Test Your Knowledge

Why is using the Rethrow activity inside a Catch block considered superior to executing a Throw activity configured with ex (Throw ex) in enterprise UiPath workflows?

A

Throw ex requires elevated administrator privileges in Windows, whereas Rethrow runs under the standard robot user account.

B

Rethrow preserves the original exception's complete stack trace and originating activity details, whereas Throw ex resets the stack trace to the catch block, hiding the original point of failure.

C

Throw ex automatically converts BusinessRuleExceptions into System.Exceptions, whereas Rethrow preserves the class type.

D

Rethrow automatically executes the Finally block twice to guarantee memory cleanup.

Test Your Knowledge

A Try Catch has three Catches listed in this order: System.Exception, System.IO.FileNotFoundException, and System.IO.IOException. The Try block throws a FileNotFoundException. Which Catch runs?

A

System.Exception, because it is listed first.

B

System.IO.IOException, because it is the direct base class.

C

None; the activity throws an AmbiguousMatchException.

D

System.IO.FileNotFoundException, because the Try Catch activity selects the most specific matching Catch regardless of its position.

Test Your Knowledge

An automation developer configures a Retry Scope activity with NumberOfRetries set to 3 and RetryInterval set to '00:00:05'. The Action block contains a Click activity and the Condition block contains an Element Exists activity. If the Click activity succeeds but the Element Exists activity evaluates to False on the first two attempts, and True on the third attempt, what is the execution sequence?

A

Action runs -> Condition evaluates to False -> 5-second delay -> Action runs -> Condition evaluates to False -> 5-second delay -> Action runs -> Condition evaluates to True -> Retry Scope exits successfully.

B

Action runs -> Condition evaluates to False -> Condition immediately re-evaluates twice more without re-executing Action -> Retry Scope exits.

C

Action runs -> Condition evaluates to False -> A System.Exception is thrown because Condition activities cannot return False.

D

Condition runs first -> Action runs -> 5-second delay -> Action runs -> Retry Scope exits successfully.

Sections you finish are checked off in the contents.