• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# System.Exception类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Exception的典型用法代码示例。如果您正苦于以下问题:C# Exception类的具体用法?C# Exception怎么用?C# Exception使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Exception类属于System命名空间,在下文中一共展示了Exception类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: WriteLog

        public void WriteLog(ICorrelation correlation, LogEventLevel eventLevel, Exception exception, string formatMessage, params object[] args)
        {
            if (log == null)
            {
                log = loggerRepository.GetLogger(sourceType);
            }

            if (eventLevel == LogEventLevel.Verbose && !log.IsDebugEnabled)
            {
                return;
            }

            if (args != null && args.Length != 0)
            {
                formatMessage = string.Format(formatMessage, args);
            }

            log4net.Core.ILogger logger = log.Logger;

            LoggingEvent logEvent = new LoggingEvent(sourceType, logger.Repository, logger.Name, MapEventLevel(eventLevel), formatMessage, exception);

            if (correlation != null)
            {
                logEvent.Properties["CallerId"] = correlation.CallerId;
                logEvent.Properties["CorrelationId"] = correlation.CorrelationId;
            }

            logger.Log(logEvent);
        }
开发者ID:affecto,项目名称:dotnet-Logging,代码行数:29,代码来源:LogWriter.cs


示例2: UnmarshallException

        public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
        {
            ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);

            if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValue"))
            {
                return new InvalidParameterValueException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterCombination"))
            {
                return new InvalidParameterCombinationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidCacheParameterGroupState"))
            {
                return new InvalidCacheParameterGroupStateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            if (errorResponse.Code != null && errorResponse.Code.Equals("CacheParameterGroupNotFound"))
            {
                return new CacheParameterGroupNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            return new AmazonElastiCacheException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
        }
开发者ID:pbutlerm,项目名称:dataservices-sdk-dotnet,代码行数:26,代码来源:DeleteCacheParameterGroupResponseUnmarshaller.cs


示例3: ConstructorWithMessageAndInnerExceptionWorks

		public void ConstructorWithMessageAndInnerExceptionWorks() {
			var inner = new Exception("a");
			var ex = new FormatException("The message", inner);
			Assert.IsTrue((object)ex is FormatException, "is FormatException");
			Assert.IsTrue(ReferenceEquals(ex.InnerException, inner), "InnerException");
			Assert.AreEqual(ex.Message, "The message");
		}
开发者ID:ShuntaoChen,项目名称:SaltarelleCompiler,代码行数:7,代码来源:FormatExceptionTests.cs


示例4: Log4NetLogger_LoggingTest

        public void Log4NetLogger_LoggingTest()
        {
            string message = "Error Message";
            Exception ex = new Exception();
            string messageFormat = "Message Format: message: {0}, exception: {1}";

            ILog log = new Log4NetLogger(GetType());
            Assert.IsNotNull(log);

            log.Debug(message);
            log.Debug(message, ex);
            log.DebugFormat(messageFormat, message, ex.Message);

            log.Error(message);
            log.Error(message, ex);
            log.ErrorFormat(messageFormat, message, ex.Message);

            log.Fatal(message);
            log.Fatal(message, ex);
            log.FatalFormat(messageFormat, message, ex.Message);

            log.Info(message);
            log.Info(message, ex);
            log.InfoFormat(messageFormat, message, ex.Message);

            log.Warn(message);
            log.Warn(message, ex);
            log.WarnFormat(messageFormat, message, ex.Message);
        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:29,代码来源:Log4NetLoggerTests.cs


示例5: Initialize

        /// <summary>
        /// Initialize the form
        /// </summary>
        public void Initialize(List<Oid> selectedOids)
        {
            mSelectedOids = selectedOids;

            // If no instances selected, inform and exit
            if (mSelectedOids == null || mSelectedOids.Count == 0)
            {
                string lMessageError = CultureManager.TranslateString(LanguageConstantKeys.L_NO_SELECTION, LanguageConstantValues.L_NO_SELECTION);
                Exception lException = new Exception(lMessageError, null);
                ScenarioManager.LaunchErrorScenario(lException);
                return;
            }

            cmbBoxSelectTemplate.SelectedIndexChanged += new EventHandler(HandlecmbBoxSelectTemplate_SelectedIndexChanged);

            // Load the templates from configuration file and fill the Combo
            LoadReportTemplates();

            // Show the number of selected instances in the Title.
            Text = CultureManager.TranslateStringWithParams(LanguageConstantKeys.L_ELEMENTSELECTED, LanguageConstantValues.L_ELEMENTSELECTED, mSelectedOids.Count);
            // Set the default printer
            lblNameOfPrint.Text = printDlg.PrinterSettings.PrinterName;

            ShowDialog();
        }
开发者ID:sgon1853,项目名称:UPM_MDD_Thesis,代码行数:28,代码来源:PrintForm.cs


示例6: LinkedINHttpResponseException

 /// <summary>
 /// Constructs an <see cref="LinkedINHttpResponseException"/>.
 /// </summary>
 /// <param name="expectedStatusCode">The expected <see cref="HttpStatusCode"/> of the response.</param>
 /// <param name="actualStatusCode">The actual <see cref="HttpStatusCode"/> of the response.</param>
 /// <param name="message">The message descriving the cause of this exception.</param>
 /// <param name="inner">The inner <see cref="Exception"/>.</param>
 public LinkedINHttpResponseException( HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, string message, Exception inner )
     : base(message, inner)
 {
     // set values
     ExpectedStatusCode = expectedStatusCode;
     ActualStatusCode = actualStatusCode;
 }
开发者ID:Gloor,项目名称:lma,代码行数:14,代码来源:LinkedINHttpResponseException.cs


示例7: ResponseShim

        internal ResponseShim(IRestResponse resp,
                              IRequestShim req,
                              string baseUrl,
                              Exception error)
        {
            this.Request = req;

            if (resp != null)
            {
                this.Code = resp.StatusCode;
                this.Message = resp.StatusDescription;
                //this.Content = Convert.ToBase64String(resp.RawBytes);
                this.Content = UTF8Encoding.UTF8.GetString(
                                resp.RawBytes, 0, resp.RawBytes.Length);
                this.IsSuccess = resp.IsSuccess;
            }

            this.BaseUrl = baseUrl;
            this.Error = error;

            var restErr = error as RestServiceException;
            if (restErr != null)
            {
                this.Code = restErr.Code;
                this.Message = restErr.Message;
            }
        }
开发者ID:peterson1,项目名称:ErrH,代码行数:27,代码来源:ResponseShim.cs


示例8: UnmarshallException

        public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
        {
            ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);

            if (errorResponse.Code != null && errorResponse.Code.Equals("ListenerNotFound"))
            {
                return new ListenerNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            if (errorResponse.Code != null && errorResponse.Code.Equals("CertificateNotFound"))
            {
                return new CertificateNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            if (errorResponse.Code != null && errorResponse.Code.Equals("LoadBalancerNotFound"))
            {
                return new LoadBalancerNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidConfigurationRequest"))
            {
                return new InvalidConfigurationRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }

            return new AmazonElasticLoadBalancingException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
        }
开发者ID:nburn42,项目名称:aws-sdk-for-net,代码行数:26,代码来源:SetLoadBalancerListenerSSLCertificateResponseUnmarshaller.cs


示例9: CalculateGeometricSum

        public static double CalculateGeometricSum(double ratio, double firstTerm, int seriesLength, int startTermNumber)
        {
            double sum = 0;
            seriesLength++;
            int nLength = seriesLength - startTermNumber;

            if(ratio == 1)
            {
                Exception ratiois1 = new Exception("The ratio is not allowed to equal 1");
                throw ratiois1;
            }

            if(startTermNumber > 1)
            {
                seriesLength--;
                nLength = seriesLength;
                sum = firstTerm * ((1 - Math.Pow(ratio, nLength)) / (1 - ratio));
                nLength = startTermNumber;
                sum -= firstTerm * ((1 - Math.Pow(ratio, nLength)) / (1 - ratio));
                return sum;
            }

            sum = firstTerm * ((1 - Math.Pow(ratio, nLength)) / (1 - ratio));

            return sum;
        }
开发者ID:MarnusStoop,项目名称:Lukas-Stoop-Code-Library,代码行数:26,代码来源:Sequences.cs


示例10: HandleConnectionError

		public void HandleConnectionError(Exception exception, PluginProfileErrorCollection errors)
		{
			_log.GetLogger("Mercurial").Warn("Check connection failed", exception);
			exception = exception.InnerException ?? exception;
			const string uriFieldName = "Uri";
			if (exception is MercurialExecutionException)
			{
                errors.Add(new PluginProfileError { FieldName = "Login", Message = ExtractValidErrorMessage(exception)});
                errors.Add(new PluginProfileError { FieldName = "Password", Message = ExtractValidErrorMessage(exception) });
                errors.Add(new PluginProfileError { FieldName = uriFieldName, Message = ExtractValidErrorMessage(exception) });
				return;
			}

            if (exception is ArgumentNullException || exception is DirectoryNotFoundException)
			{
				errors.Add(new PluginProfileError{ FieldName = uriFieldName, Message = INVALID_URI_OR_INSUFFICIENT_ACCESS_RIGHTS_ERROR_MESSAGE });
			}

            if (exception is MercurialMissingException)
            {
                errors.Add(new PluginProfileError { Message = MERCURIAL_IS_NOT_INSTALLED_ERROR_MESSAGE });
            }

			var fieldName = string.Empty;
			if (exception is InvalidRevisionException)
			{
				fieldName = "Revision";
			}

			errors.Add(new PluginProfileError {FieldName = fieldName, Message = exception.Message});
		}
开发者ID:TargetProcess,项目名称:Target-Process-Plugins,代码行数:31,代码来源:MercurialCheckConnectionErrorResolver.cs


示例11: UnmarshallException

 public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
 {
     ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
     if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException"))
     {
         return new InvalidParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
     {
         return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("OperationAbortedException"))
     {
         return new OperationAbortedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceAlreadyExistsException"))
     {
         return new ResourceAlreadyExistsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
     {
         return new ServiceUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     return new AmazonCloudWatchLogsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
 }
开发者ID:wmatveyenko,项目名称:aws-sdk-net,代码行数:25,代码来源:CreateLogGroupResponseUnmarshaller.cs


示例12: PromoteException

        //Can only be called inside a service
        public static void PromoteException(Exception error,MessageVersion version,ref Message fault)
        {
            StackFrame frame = new StackFrame(1);

             Type serviceType = frame.GetMethod().ReflectedType;
             PromoteException(serviceType,error,version,ref fault);
        }
开发者ID:JMnITup,项目名称:SMEX,代码行数:8,代码来源:ErrorHandlerHelper.cs


示例13: SendByMail

        /// <summary>
        /// Sends an error message by opening the user's mail client.
        /// </summary>
        /// <param name="recipient"></param>
        /// <param name="subject"></param>
        /// <param name="ex"></param>
        /// <param name="assembly">The assembly where the error originated. This will 
        /// be used to extract version information.</param>
        public static void SendByMail(string recipient, string subject, Exception ex,
            Assembly assembly, StringDictionary additionalInfo)
        {
            string attributes = GetAttributes(additionalInfo);

            StringBuilder msg = new StringBuilder();

            msg.AppendLine("[ Please send this as plain text to allow automatic pre-processing ]");
            msg.AppendLine();
            msg.AppendLine(GetMessage(ex));
            msg.AppendLine();
            msg.AppendLine(GetAttributes(additionalInfo));
            msg.AppendLine();
            msg.AppendLine("[ Please send this as plain text to allow automatic pre-processing ]");
            msg.AppendLine();

            string command = string.Format("mailto:{0}?subject={1}&body={2}",
                recipient,
                Uri.EscapeDataString(subject),
                Uri.EscapeDataString(msg.ToString()));

            Debug.WriteLine(command);
            Process p = new Process();
            p.StartInfo.FileName = command;
            p.StartInfo.UseShellExecute = true;

            p.Start();
        }
开发者ID:necora,项目名称:ank_git,代码行数:36,代码来源:ErrorMessage.cs


示例14: SyncWebBrowserError

 public void SyncWebBrowserError(Exception ex)
 {
     InvokeOnMainThread(() => {
         UIAlertView alertView = new UIAlertView("Sync Web Browser Error", ex.Message, null, "OK", null);
         alertView.Show();
     });
 }
开发者ID:pascalfr,项目名称:MPfm,代码行数:7,代码来源:SyncWebBrowserViewController.cs


示例15: ReportError

 protected void ReportError(Exception e)
 {
     if (Errored != null)
     {
         Errored(this, new ErrorEventArgs(e));
     }
 }
开发者ID:Coselding,项目名称:shadowsocks-windows,代码行数:7,代码来源:ShadowsocksController.cs


示例16: End

        public void End(Exception ex = null)
        {
            if (ex == null)
                sessionFactory.SaveChanges();

            sessionFactory.Dispose();
        }
开发者ID:Meksi,项目名称:NServiceBus.Persistence,代码行数:7,代码来源:DbUnitOfWork.cs


示例17: PipelineException

 /// <summary>
 /// Initializes a new instance of the PipelineException class with the specified error message and a reference to the inner exception that is the cause of this exception.
 /// </summary>
 /// <param name="message">A message that describes the error.</param>
 /// <param name="innerException">The exception that is the cause of the current exception. If innerException is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param>
 public PipelineException(
     string message,
     Exception innerException
     )
     :base(message, innerException)
 {
 }
开发者ID:GhostTap,项目名称:MonoGame,代码行数:12,代码来源:PipelineException.cs


示例18: GetWeeklySalary

        public decimal GetWeeklySalary(string employeeId, int weeks)
        {
            string connString = string.Empty;
              string employeeName = String.Empty;
              decimal salary = 0;
              try
              {
            // Access the database to get the salary for this employee.

            connString = ConfigurationManager.ConnectionStrings
                                  ["EmployeeDatabase"].ConnectionString;
            // ... etc.
            // In this example, just assume it's some large number.
            employeeName = "Jose Lopez";
            salary = 1000000;
            return salary / weeks;
              }
              catch (Exception ex)
              {
            // Provide error information for debugging.
            string template = "Error en el cálculo del salario de {0}. " +
                          "Salario: {1}. Semanas: {2}\n" +
                          "Conexion: {3}\n" +
                          "{4}";
            // Create a new exception to return.
            Exception informationException = new Exception(
              string.Format(template, employeeName, salary, weeks, connString, ex.Message));
            throw informationException;
              }
        }
开发者ID:vvalotto,项目名称:PlataformaNET,代码行数:30,代码来源:SalaryCalculator.cs


示例19: UnmarshallException

 /// <summary>
 /// Unmarshaller error response to exception.
 /// </summary>  
 /// <param name="context"></param>
 /// <param name="innerException"></param>
 /// <param name="statusCode"></param>
 /// <returns></returns>
 public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
 {
     ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
     if (errorResponse.Code != null && errorResponse.Code.Equals("InternalErrorException"))
     {
         return new InternalErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException"))
     {
         return new InvalidParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("NotAuthorizedException"))
     {
         return new NotAuthorizedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
     {
         return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
     {
         return new TooManyRequestsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
     }
     return new AmazonCognitoIdentityException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
 }
开发者ID:paveltimofeev,项目名称:aws-sdk-unity,代码行数:32,代码来源:ListIdentitiesResponseUnmarshaller.cs


示例20: LogException

 private void LogException(Exception ex)
 {
     if (MvcApplication.Logger != null)
     {
         MvcApplication.Logger.Error("MyCustomHandleError ", ex);
     }
 }
开发者ID:OleksandrKulchytskyi,项目名称:Sharedeployed,代码行数:7,代码来源:HandledErrorLoggerFilter.cs



注:本文中的System.Exception类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# System.Factory类代码示例发布时间:2022-05-26
下一篇:
C# System.EventHandler类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap