RegexMatchTimeoutException Class (System.Text.RegularExpressions) (original) (raw)

Definition

The exception that is thrown when the execution time of a regular expression pattern-matching method exceeds its time-out interval.

public ref class RegexMatchTimeoutException : TimeoutException
public class RegexMatchTimeoutException : TimeoutException
[System.Serializable]
public class RegexMatchTimeoutException : TimeoutException
type RegexMatchTimeoutException = class
    inherit TimeoutException
type RegexMatchTimeoutException = class
    inherit TimeoutException
    interface ISerializable
[<System.Serializable>]
type RegexMatchTimeoutException = class
    inherit TimeoutException
    interface ISerializable
Public Class RegexMatchTimeoutException
Inherits TimeoutException

Inheritance

RegexMatchTimeoutException

Inheritance

RegexMatchTimeoutException

Attributes

Implements

Examples

The following example illustrates two possible approaches to handling the RegexMatchTimeoutException exception. A constant whose value is two seconds defines the maximum time-out interval. The Regex.IsMatch(String, String, RegexOptions, TimeSpan) method is initially called with a time-out interval of one second. Each RegexMatchTimeoutException exception causes the time-out interval to be increased by one second and results in another call to the Regex.IsMatch method if the current time-out interval is less than the maximum time-out interval. However, if the current time-out interval exceeds the maximum time-out interval, the exception handler writes information to the event log and abandons the processing of the regular expression.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;

public class Example
{
   const int MaxTimeoutInSeconds = 2;
   
   public static void Main()
   {
      TimeSpan timeout = new TimeSpan(0, 0, 1);
      string input = "aaaaaaaaaaaaaaaaaaaaaa>";
      if (ValidateInput(input, timeout))
         // Perform some operation with valid input string.
         Console.WriteLine("'{0}' is a valid string.", input); 
   } 

   private static bool ValidateInput(string input, TimeSpan timeout)
   {
      string pattern = "(a+)+$";      
      try {
         return Regex.IsMatch(input, pattern, 
                              RegexOptions.IgnoreCase, timeout);
      }
      catch (RegexMatchTimeoutException e) {
         // Increase the timeout interval and retry.
         timeout = timeout.Add(new TimeSpan(0, 0, 1));
         Console.WriteLine("Changing the timeout interval to {0}", 
                           timeout); 
         if (timeout.TotalSeconds <= MaxTimeoutInSeconds) {
            // Pause for a short period.
            Thread.Sleep(250);
            return ValidateInput(input, timeout);
         }   
         else {
            Console.WriteLine("Timeout interval of {0} exceeded.", 
                              timeout);
            // Write to event log named RegexTimeouts
            try {
               if (!EventLog.SourceExists("RegexTimeouts"))
                  EventLog.CreateEventSource("RegexTimeouts", "RegexTimeouts");

               EventLog log = new EventLog("RegexTimeouts");
               log.Source = "RegexTimeouts";
               string msg = String.Format("Timeout after {0} matching '{1}' with '{2}.",
                                          e.MatchTimeout, e.Input, e.Pattern);
               log.WriteEntry(msg, EventLogEntryType.Error);
            }
            // Do nothing to handle the exceptions.
            catch (SecurityException) { }
            catch (InvalidOperationException) { }
            catch (Win32Exception) { }
            return false;
         }   
      }
   }
}
// The example writes to the event log and also displays the following output:
//       Changing the timeout interval to 00:00:02
//       Changing the timeout interval to 00:00:03
//       Timeout interval of 00:00:03 exceeded.
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Security
Imports System.Text.RegularExpressions
Imports System.Threading

Module Example
   Const MaxTimeoutInSeconds As Integer = 2
   
   Public Sub Main()
      Dim timeout As TimeSpan = New TimeSpan(0, 0, 1)
      
      Dim input As String = "aaaaaaaaaaaaaaaaaaaaaa>"
      If ValidateInput(input, timeout) Then
         ' Perform some operation with valid input string.
         Console.WriteLine("'{0}' is a valid string.", input) 
      End If
   End Sub 

   Private Function ValidateInput(input As String, 
                                  timeout As TimeSpan) As Boolean
      Dim pattern As String = "(a+)+$"      
      Try
         Return Regex.IsMatch(input, pattern, 
                              RegexOptions.IgnoreCase, timeout)
      Catch e As RegexMatchTimeoutException
         ' Increase the timeout interval and retry.
         timeout = timeout.Add(New TimeSpan(0, 0, 1))
         Console.WriteLine("Changing the timeout interval to {0}", 
                           timeout) 
         If timeout.TotalSeconds <= MaxTimeoutInSeconds Then
            ' Pause for a short interval.
            Thread.Sleep(250)
            Return ValidateInput(input, timeout)
         Else
            Console.WriteLine("Timeout interval of {0} exceeded.", 
                              timeout)
            ' Write to event log named RegexTimeouts
            Try
               If Not EventLog.SourceExists("RegexTimeouts") Then
                  EventLog.CreateEventSource("RegexTimeouts", "RegexTimeouts")
               End If   
               Dim log As New EventLog("RegexTimeouts")
               log.Source = "RegexTimeouts"
               Dim msg As String = String.Format("Timeout after {0} matching '{1}' with '{2}.",
                                                 e.MatchTimeout, e.Input, e.Pattern)
               log.WriteEntry(msg, EventLogEntryType.Error)
            ' Do nothing to handle the exceptions.
            Catch ex As SecurityException

            Catch ex As InvalidOperationException

            Catch ex As Win32Exception

            End Try   
            Return False
         End If   
      End Try
   End Function
End Module
' The example writes to the event log and also displays the following output:
'       Changing the timeout interval to 00:00:02
'       Changing the timeout interval to 00:00:03
'       Timeout interval of 00:00:03 exceeded.

The presence of a RegexMatchTimeoutException exception generally indicates one of the following conditions:

The way in which an exception handler handles an exception depends on the cause of the exception:

The example in the next section illustrates both techniques for handling a RegexMatchTimeoutException.

Constructors

Properties

Data Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception)
HelpLink Gets or sets a link to the help file associated with this exception. (Inherited from Exception)
HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception)
InnerException Gets the Exception instance that caused the current exception. (Inherited from Exception)
Input Gets the input text that the regular expression engine was processing when the time-out occurred.
MatchTimeout Gets the time-out interval for a regular expression match.
Message Gets a message that describes the current exception. (Inherited from Exception)
Pattern Gets the regular expression pattern that was used in the matching operation when the time-out occurred.
Source Gets or sets the name of the application or the object that causes the error. (Inherited from Exception)
StackTrace Gets a string representation of the immediate frames on the call stack. (Inherited from Exception)
TargetSite Gets the method that throws the current exception. (Inherited from Exception)

Methods

Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object)
GetBaseException() When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception)
GetHashCode() Serves as the default hash function. (Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) Obsolete. When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception)
GetType() Gets the runtime type of the current instance. (Inherited from Exception)
MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object)
ToString() Creates and returns a string representation of the current exception. (Inherited from Exception)

Events

SerializeObjectState Obsolete. Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception)

Explicit Interface Implementations

Applies to

See also