選單
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Python 教程

Python 主頁 Python 簡介 Python 入門 Python 語法 Python 註釋 Python 變數 Python 資料型別 Python 數字 Python 型別轉換 Python 字串 Python 布林值 Python 運算子 Python 列表 Python 元組 Python 集合 Python 字典 Python If...Else Python While 迴圈 Python For 迴圈 Python 函式 Python Lambda Python 陣列 Python 類/物件 Python 繼承 Python 迭代器 Python 多型 Python 作用域 Python 模組 Python 日期 Python 數學 Python JSON Python 正則表示式 Python PIP Python Try...Except Python 使用者輸入 Python 字串格式化

檔案處理

Python 檔案處理 Python 讀取檔案 Python 寫入/建立檔案 Python 刪除檔案

Python 模組

NumPy 教程 Pandas 教程 SciPy 教程 Django 教程

Python Matplotlib

Matplotlib 簡介 Matplotlib 入門 Matplotlib Pyplot Matplotlib 繪圖 Matplotlib 標記 Matplotlib 線條 Matplotlib 標籤 Matplotlib 網格 Matplotlib 子圖 Matplotlib 散點圖 Matplotlib 條形圖 Matplotlib 直方圖 Matplotlib 餅圖

機器學習

入門 均值、中位數、眾數 標準差 百分位數 資料分佈 正態資料分佈 散點圖 線性迴歸 多項式迴歸 多元迴歸 尺度 訓練/測試 決策樹 混淆矩陣 層次聚類 邏輯迴歸 網格搜尋 分類資料 K-means Bootstrap Aggregation 交叉驗證 AUC - ROC 曲線 K-近鄰

Python MySQL

MySQL 入門 MySQL 建立資料庫 MySQL 建立表 MySQL 插入 MySQL 選擇 MySQL Where MySQL Order By MySQL 刪除 MySQL 刪除表 MySQL 更新 MySQL Limit MySQL Join

Python MongoDB

MongoDB 入門 MongoDB 建立資料庫 MongoDB 集合 MongoDB 插入 MongoDB Find MongoDB Query MongoDB Sort MongoDB 刪除 MongoDB 刪除集合 MongoDB 更新 MongoDB Limit

Python 參考

Python 概述 Python 內建函式 Python 字串方法 Python 列表方法 Python 字典方法 Python 元組方法 Python 集合方法 Python 檔案方法 Python 關鍵字 Python 異常 Python 詞彙表

模組參考

Random 模組 Requests 模組 Statistics 模組 Math 模組 cMath 模組

Python 如何操作

刪除列表重複項 反轉字串 兩個數字相加

Python 示例

Python 示例 Python 編譯器 Python 練習 Python 測驗 Python 伺服器 Python 面試問答 Python 訓練營 Python 證書

Python Try Except


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.


異常處理

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement

示例

The try block will generate an exception, because x is not defined

try
  print(x)
except
  print("An exception occurred")
自己動手試一試 »

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error

示例

This statement will raise an error, because x is not defined

print(x)
自己動手試一試 »

多種異常

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error

示例

Print one message if the try block raises a NameError and another for other errors

try
  print(x)
except NameError
  print("Variable x is not defined")
except
  print("Something else went wrong")
自己動手試一試 »


Else

You can use the else keyword to define a block of code to be executed if no errors were raised

示例

In this example, the try block does not generate any error

try
  print("Hello")
except
  print("Something went wrong")
else
  print("Nothing went wrong")
自己動手試一試 »

Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

示例

try
  print(x)
except
  print("Something went wrong")
finally
  print("The 'try except' is finished")
自己動手試一試 »

This can be useful to close objects and clean up resources

示例

Try to open and write to a file that is not writable

try
  f = open("demofile.txt")
  try
    f.write("Lorum Ipsum")
  except
    print("Something went wrong when writing to the file")
  finally
    f.close()
except
  print("Something went wrong when opening the file")
自己動手試一試 »

The program can continue, without leaving the file object open.


引發異常

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

示例

Raise an error and stop the program if x is lower than 0

x = -1

if x < 0
  raise Exception("Sorry, no numbers below zero")
自己動手試一試 »

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

示例

Raise a TypeError if x is not an integer

x = "hello"

if not type(x) is int
  raise TypeError("Only integers are allowed")
自己動手試一試 »


×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援