From JavaScript to Python's anomaly

Many front-end engineers saw this headline may be generated asked:

I js used properly, can be back-end can APP, why bother to learn Python?

There are at least the following two reasons:

  1. learning curve. JavaScript (TypeScript) after ES6 syntactically similar to and Python have a lot of places, so the learning curve is very smooth, difficult to get started is very low.
  2. Scenarios. Although web development JavaScript is king, but still there are some problems in some areas. For example, although you can write Node.js backend, but mostly for CGI layer, as interface and integration template rendering, and Python, Java has been widely used such language to write back-end services, while Python in terms of machine learning, also do great advantage.

In this article we learn Python by "abnormal" contrast between the two languages.

Why do we need to deal with exceptions

An exception is a problem that must be considered when writing code, but it is not a hot topic, rarely mentioned in the article.
Especially in the web front end of this one, strong fault tolerance capabilities of the browser to help engineers solve (hide) a number of exception.
But if you ignore anomalies ranging from affecting the operation of the function, while in lead to system crashes, resulting in economic losses.

Exception Handling

capture

JavaScript exception caught with the same keyword Python, are using try.

// JavaScript
try {
  ...
}
# Python
try:
  ...

But both have limitations: only be used to capture abnormal synchronization code execution.

In the case of abnormal trapped asynchronous JavaScript code is relatively complex to deal with, according to the operating environment can be divided into Node.js and browser, press the capture range can be divided into whole and partial capture capture.

// 浏览器全局异常捕获
window.onError = e => {}  
window.addEventListener('', e => {}) 捕获请求错误
// 浏览器Ajax异常捕获
var xhr = new XMLHttpRequest();
xhr.onload = function(e) { 
  if(this.status > 400){
    ...
  }
};
// Node.js 全局异常捕获
process.on('uncaughtException', e => {})
// Node.js 回调方式异常捕获
fs.readFile('/etc/passwd', (err, data) => {
  if (err) {
    ...
  }
});

Python is much simpler case, even with asynchronous thread or process can also be captured inside a function, then other ways reported.

def _parse_speed(key_name, speed_list):
  try:
    ...

t = threading.Thread(target=_parse_speed, args=(v, speed_list))
t.start()

Due to capture abnormal situation is more complicated, if no special instructions, the discussion refers only to later try to use keywords to capture synchronous exceptions.

deal with

JavaScript look at several ways to handle exceptions.

  • catch. catch block for processing exception handling is quite extensive, all exceptions are in try blocks are captured.
  • finally. finally block represents whether or not an exception occurs, the statement block of code will be executed.

Many readers may think the code to execute after the catch block and finally block the same effect, but in fact there is a difference!

Below is an example

fn = () => {
  try {
    throw Error()
  } catch(e) {
    throw Error()
    return 1
  } finally {
    return 2
  }
  return 3
}
fn() // 是2不是3

That finally block code, regardless of try or catch execution error will be executed.

Python exception handling:

  • except. You can specify multiple exception types to be processed, there may be a plurality of exception handling logic, writing is very flexible.
  • else. else block may be performed when abnormality occurs in the try block is not.
  • finally. Properties with JavaScript.

The following are a few examples of use except:

# 捕获异常实例
except Exception as e:

# 批量异常捕获
except (IOError, TypeError):

# 异常分类捕获:
except OSError as err:
  ...
except ValueError:
  ...
except:
  ...

Throw out

JavaScript can be used to throw an Error object by keyword throw.
Python corresponding thereto is raise, for instance throws an Exception.

Although keywords are not the same, but the wording is substantially similar:

// JavaScript
throw Error(...)
# Python
raise Exception(...)

Exception Type

For JavaScript, the talk of little significance exception classes, exceptions need to manually handle different judgment, so the exception type is relatively simple.

js-error.jpg

Python exception types are much more abundant


py-error.jpg

to sum up

  • Capture aspect, JavaScript complex scenes than Python, transfer learning Python is simple.
  • Processing, both of which support finally keyword. Except that the operation is simplified JavaScript, only exception to handle all types by a catch block. The Python practices consistent with most high-level languages, many times, were treated for different anomalies, else regarded as a key features.
  • Thrown aspects, both just different keywords.

reference:

Guess you like

Origin blog.51cto.com/14160840/2425523