Home Backend Development C#.Net Tutorial What is the error handling mechanism of .net

What is the error handling mechanism of .net

Apr 26, 2019 pm 01:35 PM
.net Error handling mechanism

.NET's error handling mechanism is: 1. [Page_Error] event; 2. ErrorPage attribute; 3. [Application_Error] event; 4. [] configuration item. The above four processing mechanisms are mainly used for exception handling and page-level error handling.

What is the error handling mechanism of .net

.NET provides four error handling mechanisms:

1.Page_Error event

The Page_Error event provides a way to capture errors that occur at the page level. You can simply display an error message (as shown in the sample code below), log an event, or perform some other action.

private void Page_Load(object sender, System.EventArgs e)
   { // Put user code to initialize the page here
        throw new Exception("Page Error!");
   }
protected void Page_Error(object sender, EventArgs e) 
   {
      Exception objErr = Server.GetLastError().GetBaseException();
    Response.Write("Error:" + objErr.Message);
       Server.ClearError(); //同样要注意这句代码的使用
  }
Copy after login

Note: This example displays a detailed error message in the browser and is provided for illustration only. Be careful when displaying detailed information to the end users of your application. It is more appropriate to display a message to the user that an error has occurred and then log the specific error details.

2. ErrorPage property

You can set the ErrorPage property almost at any time on the page to determine which page it will redirect to when an error occurs on the page. For the ErrorPage attribute to work, the mode attribute in the configuration item must be set to "On".

this.ErrorPage = "~/ErrorHandling/PageError.html";
Copy after login

If Page_Error and ErrorPage both exist, what is the order of page execution when an Exception is thrown? The page will first execute the Page_Error event processing function. If the function Server.ClearError() is called in the Page_Error() event to clear the exception information, it will not jump to the page specified by the ErrorPage attribute; if Server.ClearError() is not called, the Exception information will continue. Throw it upward and the page will jump to the page specified by ErrorPage. This also proves the order of priority: Page_Error event > ErrorPage attribute.

3.Application_Error event

Similar to the Page_Error event, you can use the Application_Error event to capture errors that occur in the application. Because events occur application-wide, you can log application error information or handle other application-level errors that may occur. Add the following code to the Global.asax file and it will be OK.

protected void Application_Error(object sender, EventArgs e)
      {
         Exception ex = Server.GetLastError().GetBaseException();
         //实际应用中这里可以将Exception信息记Log或是保存到数据库中
         //还可以将错误发邮件给网站维护人员
          Response.Write("Error:" + ex.Message);
         //清除Exception,避免继续传递给上一级处理
         //这里上级就是<CustomerErrors>配置节了
          Server.ClearError(); 
     }
Copy after login

4. Configuration item

The configuration section in the configuration file web.config can specify the redirect page as the default Error page defaultRedirect or specify a specific page based on the HTTP error code raised. This custom page is displayed if an error occurs that was not caught at any previous level of the application.

<customErrors mode="On" defaultRedirect="~/ErrorHandling/ApplicationError.html"> <error statusCode="404" redirect="~/ErrorHandling/404.html" /> </customErrors>
Copy after login

Similarly, if Application_Error and exist at the same time, there is also a problem of execution order. Because the priority Application_Error event> configuration item, when an application-level error occurs, the code in the Application_Error event is executed first. If the Server.ClearError() function is called in the Application_Error event, the configuration section The defaultRedirect does not work because the Exception has been cleared; if the Server.ClearError() function is not called in the Application_Error event, the error page will be relocated to the URL page specified by defaultRedict to display a friendly error message to the user.

Through the analysis of the above four error handling mechanisms provided by .NET, we can classify them from different perspectives to facilitate our understanding and use.

1. Functionally classified: used for exception handling (Handling exceptions) are the Page_Error event and Application_Error event; for user error page redirection (Redirecting the user to an error page) are the ErrorPage attribute and

2. Classification from the scope of error handling: Page_Error event and ErrorPage attribute are used for page level error handling; Application_Error event and < are used for application level error handling. ;customErrors>Configuration item.

The above is the detailed content of What is the error handling mechanism of .net. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

New error handling mechanism in PHP8.0: throwable interface New error handling mechanism in PHP8.0: throwable interface May 14, 2023 am 08:21 AM

In PHP8.0, a very important update is the improvement of the error handling mechanism, which introduces a new interface-throwable. This interface includes two exception types, Error and Exception, so that developers do not need to distinguish between errors and exceptions that comply with catchable exception specifications. Below, we will introduce the throwable interface in detail. What is throwable? Throwable is a new interface introduced in PHP8.0, including Error and Excepti

.NET performance optimization technology for developers .NET performance optimization technology for developers Sep 12, 2023 am 10:43 AM

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

Performance differences between Java framework and .NET framework Performance differences between Java framework and .NET framework Jun 03, 2024 am 09:19 AM

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.

C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

See all articles