


.NET Framework-detailed explanation of exception design principles
Frontier
Exception design guidelines, refer to Microsoft msdn, combine your own understanding and the handling of exception errors in past development, summarize the software development architecture, and how to better design A set of exception error guidelines.
Introduction to guidelines
Execution failure concept
The meaning of execution failure: execution failure occurs whenever a member cannot do what it was designed to do (what the member name implies). For example, if the OpenFile method cannot return an opened file handle to the caller, it would be considered an execution failure.
Translation:
The meaning of operation failure: Whenever a member module cannot complete its expected task, it is said that an operation failure has occurred. For example, the OpenFile method cannot return a handle to the open file to the caller, which is an operation failure.
Handling Exceptions in the Framework
In the Framework, exceptions are used for all error conditions, including execution errors.
Translation:
In the framework, exceptions are used to handle all error conditions, including execution errors.
Summary Guidelines
Which methods should be prohibited when designing exceptions, which should be done without hesitation, and which should be considered, are listed in the table below.
Number | Method | How to do |
---|---|---|
1 | Return error code | Prohibited |
2 | Execution error, to Throws an exception; if OpenFile() does not return a file handle | Recommendations |
3 | If the code becomes unsafe to continue execution, Consider whether to call System.Environment.FailFast to terminate the process or throw an exception. | Consider |
4 | If possible, throw an exception at the normal control flow, see the analysis below | Prohibition |
5 | The impact of throwing exceptions on performance. | Consider |
6 | Incorporate exception handling part into the agreement | Suggestions |
7 | Return exceptions as return values | Prohibited |
8 | Use the exception generator method to avoid code bloat , use helper methods to create exceptions and properties. | Consider |
9 | Throwing exceptions in exception filters. | Disallowed |
10 | Explicitly throwing exceptions from finally blocks | Forbidden |
Explanation on Article 4:
In daily coding, consider the Tester-Doer pattern for members that may throw exceptions in common scenarios to avoid performance problems related to exceptions. The Tester-Doer pattern pides a call that might throw exceptions into two parts: a Tester and a Doer. The Tester performs a test for the state that can cause the Doer to throw an exception . The test is inserted just before the code that throws the exception, thereby guarding against the exception. Reference example from http://blog.csdn.net/troubleshooter/article/details/18401491
Code:
Tester and Doer perform their respective duties, perfectly reducing exception throwing and improving performance.
Doer: The above status monitoring is good before it can be processed by DoProcess(); if it is false, and if DoProcess() includes DoCheck() logic, an exception will be thrown, but this way After separation, DoProcess() will not throw an exception!
if(DoCheck()==true)//这是Tester:状态监测 DoProcess();
Common exceptions and handling methods in software development (own summary)
1 It is recommended to wrap the operation interface exposed by the UI layer with a try{}catch{} block, write the thrown exception to disk in catch.
2 When a timer is used in the UI layer, after an exception occurs in the counter's callback function, the timer must be stopped to prevent the error log from being written to the file.
3 The bottom layer is not recommended to wrap the try{}catch{} block. It is recommended to use throw to throw an exception directly. Because the try{} and catch{} blocks are wrapped on the UI layer, there is no It is necessary to write in these layers.
4 throw will directly interrupt future operations and jump to the outer stack try{} and catch{}, that is, the UI layer. Taking advantage of this property, it is generally recommended that functions do not return error codes.
5 When processing batch-imported data, a local exception occurred. Excel imports personnel, equipment, plans, materials, processes, etc. If a certain row of data violates the rules, it is not recommended to throw an exception at this time, because once an exception is thrown, it means that the data in the following rows cannot be imported, and the data that has been imported becomes dirty data.
Generally, there are two approaches: illegal data appears in a certain row and is recorded in the log file. In the future, based on this file, it is found that the data has not been imported, and then this one can be processed separately; Before importing, check directly After checking whether the data in all rows are legal, import one by one. Otherwise, a prompt will pop up and no data will be written to the database. It is generally recommended to do the latter. This approach is called: Tester-Doer exception mode, which is also recommended by Microsoft.
6 When processing the kanban display data, a local exception occurred. This processing mode is different from 5. Generally, when an exception occurs at this time, the former method of 5 is often adopted: displays the correct data, and writes the illegal data to the log for review; but it is also possible , if the main data in the displayed interface does not exist, an exception will be thrown directly, written to the log, and solved through the log. Therefore, it should be processed according to the abnormality severity of the data.
7 Based on development documents, logs, and analysis, try to find the reason why a certain function is not implemented. First, keep the development documents and check whether the current user requirements are consistent with those in the development documents. If they are consistent, the role of the log will be displayed at this time. For example, a pie chart summarizing the completion of all processes within a week. If there is no process data, then the pie chart may not exist. During the development process, if you check whether It does not mean that there is a process. If a process is not found, an exception may be thrown. If the process is written to the log, the reason will be found. Therefore, this type of problem should also be written to the log. Although it is not an error, it can be classified as an exception.
8 The function returns an object whose methods and properties are referenced by subsequent logic. This is inevitable! And the implementation of most functions depends on this. Because the returned object will be referenced later, It is recommended to do a null comparison. If it is null, should it be passed to the UI layer and a message prompt will pop up, or an exception will be thrown directly. The UI layer will write it to the log after processing, depending on the situation. Certainly.
The above is the detailed content of .NET Framework-detailed explanation of exception design principles. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to solve the Java thread interrupt timeout exception (ThreadInterruptedTimeoutException). In Java multi-thread programming, we often encounter situations where the thread execution time is too long. In order to prevent threads from occupying too many system resources, we usually set a timeout. When the thread execution time exceeds the timeout, we hope to be able to interrupt the execution of the thread. Java provides a thread interruption mechanism. By calling the thread's interrupt() method, you can

Java is one of the most widely used programming languages, but when developing applications using Java, it is easy to encounter "OutOfMemoryError" exception errors, which often bring some challenges to developers. What exactly causes the OutOfMemoryError exception in Java? Next, let’s take a closer look. Memory Leak (MemoryLeak) Memory leak refers to when an object cannot be recycled by the garbage collector, it will cause a memory leak.

The abnormality in the pool is a side task in the game. Many players want to know how to complete the abnormality in the pool task. It is actually very simple. First, we must master the technique of shooting in the water before we can accept the task and investigate the source of the stench. Later, we discovered It turns out that there are a lot of corpses under the pool. Let’s take a look at this graphic guide for the unusual tasks in the pool in Rise of Ronin. Guide to unusual missions in the Ronin Rise Pool: 1. Talk to Iizuka and learn the technique of shooting in the water. 2. Go to the location in the picture below to receive the abnormal task in the pool. 3. Go to the mission location and talk to the NPC, and learn that there is a foul smell in the nearby pool. 4. Go to the pool to investigate. 5. Swim to the location in the picture below, dive underwater, and you will find a lot of corpses. 6. Use a camera to take pictures of the corpse. 7

Methods to solve Java reflection exceptions (ReflectiveOperationException) In Java development, reflection (Reflection) is a powerful mechanism that allows programs to dynamically obtain and operate classes, objects, methods, properties, etc. at runtime. Through reflection, we can implement some flexible functions, such as dynamically creating objects, calling private methods, obtaining class annotations, etc. However, using reflection also brings some potential risks and problems, one of which is reflection anomalies (

Practical tips for efficiently resolving large file read exceptions in Java require specific code examples. Overview: When processing large files, Java may face problems such as memory overflow and performance degradation. This article will introduce several practical techniques to effectively solve Java large file reading exceptions, and provide specific code examples. Background: When processing large files, we may need to read the file contents into memory for processing, such as searching, analyzing, extracting and other operations. However, when the file is large, the following problems are often encountered: Memory overflow: trying to copy the entire file at once

Today I would like to introduce to you an article published by MIT last week, using GPT-3.5-turbo to solve the problem of time series anomaly detection, and initially verifying the effectiveness of LLM in time series anomaly detection. There is no finetune in the whole process, and GPT-3.5-turbo is used directly for anomaly detection. The core of this article is how to convert time series into input that can be recognized by GPT-3.5-turbo, and how to design prompts or pipelines to let LLM solve the anomaly detection task. Let me introduce this work to you in detail. Image paper title: Largelanguagemodelscanbezero-shotanomalydete

Exception handling and unit testing are important practices to ensure the soundness of C++ code. Exceptions are handled through try-catch blocks, and when the code throws an exception, it jumps to the catch block. Unit testing isolates code testing to verify that exception handling works as expected under different circumstances. Practical case: The sumArray function calculates the sum of array elements and throws an exception to handle an empty input array. Unit testing verifies the expected behavior of a function under abnormal circumstances, such as throwing an std::invalid_argument exception when an array is empty. Conclusion: By leveraging exception handling and unit testing, we can handle exceptions, prevent code from crashing, and ensure that the code behaves as expected under abnormal conditions.

How to solve the Java network connection reset exception (ConnectionResetException) When doing Java network programming, you often encounter the network connection reset exception (ConnectionResetException). This exception means that after the connection is established, the other host accidentally closed the connection. This may be caused by a crash of the other party's host, network interruption, or firewall configuration. When writing network applications, we need to handle this exception to ensure that the program can run normally
