32 Answering How to Choose the Proper Exception Handling Method

32 Answering How to Choose the Proper Exception Handling Method #

Hello, I’m Jingxiao.

Unknowingly, we have completed the study of the third major chapter - the chapter on specifications. I am delighted to see that many students have been actively studying and have left many high-quality comments that deserve our mutual reflection and communication. Some students have also carefully thought about and pointed out some expressions in the articles that were not rigorous or inappropriate, and I am very grateful for that.

I have replied to most of the comments in the corresponding articles. For some comments that are not convenient to reply to on mobile devices or for valuable and typical questions, I have compiled them as today’s Q&A content and will respond to them collectively.

Question 1: Which way should be used for exception handling? #

The first question is from Code2. Which style of exception handling, the first or the second, is more effective and elegant?

  • The first style directly detects and handles data in the code and throws exceptions.
  • The second style handles exceptions in the exception handling code.

In fact, the first method can be translated into the following “if…elif…” statement:

if [condition1]:
    raise Exception1('exception 1')
elif [condition2]:
    raise Exception2('exception 2')
...

While the second method corresponds to the following exception handling code:

try:
    ...
except Exception as e:
    ...

One very important difference between these two methods is that once an exception is thrown in the first method, the program will terminate. In the second method, if an exception is thrown, it will be caught by the program and the program will continue to run. This is also an important basis for choosing between these two methods. Of course, in actual work, which method to use depends on the specific scenario.

For example, if a module’s function is to check input, and if the input is invalid, a dialog box pops up to prompt the user and the program terminates, then using the first method is more reasonable.

However, if it is a server-side of a product that needs to handle various possible situations to ensure that the server does not crash, such as when connecting to a database, if there is a network exception and cannot establish a connection, then it is necessary to catch this exception, log it, and ensure that other functions are not affected. In this case, we usually choose the second method.

Question 2: Is it okay to write code that works first and then optimize it later? #

In the second question, the student mentioned the “words of wisdom” often shared by programmers, which is to write code that works first and then optimize it later. It is clear that this understanding is incorrect. From the very beginning of writing code, we must focus on both functionality and standards.

The priority of code functionality and code standards is equal, and they should be addressed simultaneously. If you only focus on getting the code to work initially without considering its quality and standards, then issues with standards are likely to accumulate. This will result in more bugs in the product and make the codebase increasingly difficult to maintain, eventually requiring a complete rebuild.

I have encountered such situations while working at Facebook and have been involved in similar projects. At that time, due to time constraints, code reviews were lenient and the code was not written according to standards, leaving behind potential risks. Over time, more and more bugs and legacy issues emerged. In the end, with no other options, a few of us engineers had to propose a project and spent over three months rewriting the code for this module in order to solve the problem.

Question 3: How many comments should be written in the code? #

The third question comes from a comment by my fellow coder, Long Xuanfeng. He mentioned that his colleague requires 70% of the code to be commented, which seems excessive. However, on the other hand, if there are no or very few comments in your code, relying solely on well-named variables is definitely not enough.

Usually, we would add a descriptive comment at the beginning of a class, function, or a specific block of code to explain the functionality and indicate all the inputs and outputs. In addition to that, we also recommend adding comments above some tricky code to help readers understand its meaning.

In general, there is no unified requirement for how many comments should be in the code. It depends on the code size and complexity. However, as long as we follow these guidelines, it should be sufficient.

Furthermore, it is important to note that if you make changes to the code after writing it, the corresponding comments must be modified accordingly. Otherwise, it is easy to cause confusion and difficulties for both yourself and others.

Question 4: Are project API documents important? #

The fourth question comes from a student named “Wei Lai Yi Lai”. He mentioned the importance of project API documents, which is a very good point. I will briefly introduce it here.

In this column, I mainly talk about the issue of code standards, but in many cases, having well-structured code is not enough. This is because a system, a product, or even a module of functionality can be very complex. It can range from a few thousand lines to hundreds of thousands of lines of code. Especially for newcomers who have just joined, it can be a nightmare to just read the code during the ramp-up stage.

Therefore, companies that do things more systematically in this aspect usually require documentation. Project documentation mainly provides an overview of the corresponding system, product, or module, which helps future developers understand it. Taking a service as an example, its corresponding documentation usually includes the following parts:

  • The first part is an overview of the system, including an introduction to the various components and workflow.
  • The second part is a specific introduction to each component, including its necessity, design principles, etc.
  • The third part is about the performance of the system, including parameters such as latency.
  • The fourth part mainly explains how to make modifications to various parts of the system, providing code pointers and corresponding test plans.

I hope you can remember these contents as well.

Today, I primarily answered these questions, and I welcome you to continue writing your questions and thoughts in the comments section. I will continue to provide answers. I hope that each comment and Q&A session can bring you new insights and value.