在一行中捕獲多個異常(塊除外) - Catch multiple exceptions in one line (except block)
問題:
I know that I can do:我知道我可以做到:
try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
I can also do this:我也可以這樣做:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladder
But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:但是如果我想在兩個不同的異常中做同樣的事情,我現在能想到的最好的就是這樣做:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say please
Is there any way that I can do something like this (since the action to take in both exceptions is to say please
):有什麼辦法可以做這樣的事情(因為在這兩個例外中採取的行動都是say please
):
try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say please
Now this really won't work, as it matches the syntax for:現在這真的行不通了,因為它匹配以下語法:
try:
# do something that may fail
except Exception, e:
# say please
So, my effort to catch the two distinct exceptions doesn't exactly come through.所以,我努力捕捉這兩個不同的異常並沒有完全實現。
Is there a way to do this?有沒有辦法做到這一點?
解決方案:
參考一: https://stackoom.com/question/R9Fk參考二: Catch multiple exceptions in one line (except block)
「其他文章」
- 如何在 JavaScript 中編寫內聯 IF 語句? - How to write an inline IF statement in JavaScript?
- 如何限制 Parallel.ForEach? - How can I limit Parallel.ForEach?
- python:如何識別變數是陣列還是標量 - python: how to identify if a variable is an array or a scalar
- 使用 Windows 命令提示符安裝 Windows 服務? - Install a Windows service using a Windows command prompt?
- 如何在沒有我自己的登錄檔的情況下安裝私有 NPM 模組? - How to install a private NPM module without my own registry?
- 如何使用 pip 更新/升級包? - How to update/upgrade a package using pip?
- 條件使用NOT NIL的Rails - Rails where condition using NOT NIL
- 像屬性一樣訪問字典鍵? - Accessing dict keys like an attribute?
- 檔案輸入“接受”屬性 - 有用嗎? - File input 'accept' attribute - is it useful?
- Python while 語句上的 Else 子句 - Else clause on Python while statement
- 正則表示式匹配兩個單詞之一 - Regex match one of two words
- 我們如何下載 blob url 影片 [關閉] - How do we download a blob url video [closed]
- 比較兩個字串,忽略 C# 中的大小寫 [重複] - Comparing two strings, ignoring case in C# [duplicate]
- Java 介面/實現命名約定 [重複] - Java Interfaces/Implementation naming convention [duplicate]
- 如何檢查是否在 Cygwin、Mac 或 Linux 中執行? - How to check if running in Cygwin, Mac or Linux?
- Java 日期與日曆 - Java Date vs Calendar
- 在 JavaScript 中將日期轉換為另一個時區 - Convert date to another timezone in JavaScript
- 為SQL Server Express 2012啟用遠端連線 - Enable remote connections for SQL Server Express 2012
- 如何從程式碼中獲取裝置的IP地址? - How to get IP address of the device from code?
- 獲取簡短的 Git 版本雜湊 - Get the short Git version hash