đŸ•ˇī¸ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 13 (from laksa153)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

â„šī¸ Skipped - page is already crawled

📄
INDEXABLE
✅
CRAWLED
3 days ago
🤖
ROBOTS SERVER UNREACHABLE
Failed to connect to robots server: Operation timed out after 2002 milliseconds with 0 bytes received

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.1 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://note.nkmk.me/en/python-try-except-else-finally/
Last Crawled2026-04-10 20:51:06 (3 days ago)
First Indexed2020-12-31 06:56:01 (5 years ago)
HTTP Status Code200
Meta TitleTry, except, else, finally in Python (Exception handling) | note.nkmk.me
Meta DescriptionIn Python, try and except are used to handle exceptions. Additionally, else and finally can be used to define actions to take at the end of the try-except process. 8. Errors and Exceptions - Handling ...
Meta Canonicalnull
Boilerpipe Text
In Python, try and except are used to handle exceptions. Additionally, else and finally can be used to define actions to take at the end of the try-except process. 8. Errors and Exceptions - Handling Exceptions — Python 3.11.3 documentation 8. Compound statements - The try statement — Python 3.11.3 documentation Contents Basic exception handling in Python: try ... except ... Catch a specific exception Store the exception object Work with base classes Flow when an exception occurs Catch multiple exceptions Apply different operations to multiple exceptions Apply the same operation to multiple exceptions Catch all exceptions Wildcard except (Bare except) Base class: Exception Execute action if no exception occurs: try ... except ... else ... Clean-up action: try ... except ... finally ... Ignore exceptions: pass Practical example: Reading image files Without exception handling With exception handling You can also set up debugging assertions with the assert statement. The assert statement in Python Basic exception handling in Python: try ... except ... Catch a specific exception For example, when attempting division by zero, a ZeroDivisionError is raised, causing the process to end. # print(1 / 0) # ZeroDivisionError: division by zero To catch this exception, use try and except as follows: try : print ( 1 / 0 ) except ZeroDivisionError : print ( 'Error' ) # Error Store the exception object By using except <exception-name> as <variable-name>: , the exception object is stored in the variable. You can choose any name for the variable, but names like e and err are commonly used. The exception object contains error messages that are displayed when an exception occurs, allowing you to check the error details by outputting them. try : print ( 1 / 0 ) except ZeroDivisionError as e : print ( e ) print ( type ( e )) # division by zero # <class 'ZeroDivisionError'> In Python 2, it should be written as except <exception-name>, <variable-name>: . Work with base classes You can also specify a base class. For example, ArithmeticError is the base class for ZeroDivisionError . The variable stores the exception object of the derived class that actually occurred. print ( issubclass ( ZeroDivisionError , ArithmeticError )) # True try : print ( 1 / 0 ) except ArithmeticError as e : print ( e ) print ( type ( e )) # division by zero # <class 'ZeroDivisionError'> Check the official documentation for built-in exceptions in Python. Built-in Exceptions — Python 3.11.4 documentation Flow when an exception occurs When an exception occurs in the try clause, the subsequent code in the try clause is skipped. For example, if an exception occurs in the middle of the for loop, the loop ends at that point, and the code in the except clause is executed. try : for i in [ - 2 , - 1 , 0 , 1 , 2 ]: print ( 1 / i ) except ZeroDivisionError as e : print ( e ) # -0.5 # -1.0 # division by zero You can specify the code to execute after the except clause using the else and finally clauses, which will be described later. Catch multiple exceptions Define the following function that catches ZeroDivisionError . def divide ( a , b ): try : print ( a / b ) except ZeroDivisionError as e : print ( 'catch ZeroDivisionError:' , e ) This function can catch ZeroDivisionError , but it cannot catch other exceptions. divide ( 1 , 0 ) # catch ZeroDivisionError: division by zero # divide('a', 'b') # TypeError: unsupported operand type(s) for /: 'str' and 'str' Apply different operations to multiple exceptions You can use multiple except clauses to handle different exceptions with different operations. def divide_each ( a , b ): try : print ( a / b ) except ZeroDivisionError as e : print ( 'catch ZeroDivisionError:' , e ) except TypeError as e : print ( 'catch TypeError:' , e ) divide_each ( 1 , 0 ) # catch ZeroDivisionError: division by zero divide_each ( 'a' , 'b' ) # catch TypeError: unsupported operand type(s) for /: 'str' and 'str' Apply the same operation to multiple exceptions You can specify multiple exception names in a single except clause by using a tuple . def divide_same ( a , b ): try : print ( a / b ) except ( ZeroDivisionError , TypeError ) as e : print ( e ) divide_same ( 1 , 0 ) # division by zero divide_same ( 'a' , 'b' ) # unsupported operand type(s) for /: 'str' and 'str' Catch all exceptions You can also catch all exceptions without specifying them. Wildcard except (Bare except) All exceptions can be caught by omitting the exception name from the except clause. If there are multiple except clauses, the exception name can be omitted only in the last except clause. The use of an except clause without specifying the exception name is referred to as a wildcard except or bare except, and as mentioned in the official documentation, caution should be exercised when using it. The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! 8. Errors and Exceptions - Handling Exceptions — Python 3.9.0 documentation def divide_wildcard ( a , b ): try : print ( a / b ) except : print ( 'Error' ) divide_wildcard ( 1 , 0 ) # Error divide_wildcard ( 'a' , 'b' ) # Error Using a wildcard except, you can catch all exceptions, including SystemExit (raised by sys.exit() , etc.) and KeyboardInterrupt (triggered by pressing Ctrl + C ). However, it's often preferable not to catch these particular exceptions. In such cases, using Exception instead may be a better option, as described next. Base class: Exception You can specify Exception in the except clause, which is the base class for all built-in, non-system-exiting exceptions. Built-in Exceptions - Exception — Python 3.11.3 documentation def divide_exception ( a , b ): try : print ( a / b ) except Exception as e : print ( e ) divide_exception ( 1 , 0 ) # division by zero divide_exception ( 'a' , 'b' ) # unsupported operand type(s) for /: 'str' and 'str' The class hierarchy for built-in exceptions is as follows. Built-in Exceptions - Exception hierarchy — Python 3.11.3 documentation BaseException ├── BaseExceptionGroup ├── GeneratorExit ├── KeyboardInterrupt ├── SystemExit └── Exception ├── StopAsyncIteration ├── StopIteration ├── ... ... Since SystemExit and KeyboardInterrupt do not inherit from Exception , using Exception in the except clause will not catch sys.exit() or interrupts like Ctrl + C . Built-in Exceptions - SystemExit — Python 3.11.3 documentation Built-in Exceptions - KeyboardInterrupt — Python 3.11.3 documentation The base class for all built-in exceptions, including SystemExit and KeyboardInterrupt , is BaseException . If you specify BaseException instead of Exception in the except clause, all exceptions will be caught. Built-in Exceptions - BaseException — Python 3.11.3 documentation It is better to specify the expected exceptions in the except clause as much as possible, because catching an unexpected exception may lead to a bug. Execute action if no exception occurs: try ... except ... else ... You can use the else clause to specify an action to be executed if no exception occurs. If an exception does occur and is caught by an except clause, the action in the else clause will not be executed. def divide_else ( a , b ): try : print ( a / b ) except ZeroDivisionError as e : print ( 'catch ZeroDivisionError:' , e ) else : print ( 'finish (no error)' ) divide_else ( 1 , 2 ) # 0.5 # finish (no error) divide_else ( 1 , 0 ) # catch ZeroDivisionError: division by zero Clean-up action: try ... except ... finally ... In the finally clause, you can specify the clean-up action to be executed whether an exception occurs or not. def divide_finally ( a , b ): try : print ( a / b ) except ZeroDivisionError as e : print ( 'catch ZeroDivisionError:' , e ) finally : print ( 'all finish' ) divide_finally ( 1 , 2 ) # 0.5 # all finish divide_finally ( 1 , 0 ) # catch ZeroDivisionError: division by zero # all finish You can also use the else and finally clause together. If no exception occurs, the else clause is executed and then the finally clause is executed. def divide_else_finally ( a , b ): try : print ( a / b ) except ZeroDivisionError as e : print ( 'catch ZeroDivisionError:' , e ) else : print ( 'finish (no error)' ) finally : print ( 'all finish' ) divide_else_finally ( 1 , 2 ) # 0.5 # finish (no error) # all finish divide_else_finally ( 1 , 0 ) # catch ZeroDivisionError: division by zero # all finish Ignore exceptions: pass If you want to catch an exception and continue without taking any action, use pass . def divide_pass ( a , b ): try : print ( a / b ) except ZeroDivisionError : pass divide_pass ( 1 , 0 ) See the following article for details on the pass statement. The pass statement in Python Practical example: Reading image files A convenient example of using exception handling is reading image files. The following is an example of resizing image files in a folder using Pillow. Resize images with Python, Pillow Without exception handling Get all file paths in the folder with glob() and resize only files that match specific extensions. How to use glob() in Python Get the filename, directory, extension from a path string in Python The in operator in Python (for list, string, dictionary, etc.) import os import glob from PIL import Image dst_dir = 'data/temp/images_half' os . makedirs ( dst_dir , exist_ok = True ) files = glob . glob ( './data/temp/images/*' ) for f in files : root , ext = os . path . splitext ( f ) if ext in [ '.jpg' , '.png' ]: img = Image . open ( f ) img_resize = img . resize (( img . width // 2 , img . height // 2 )) basename = os . path . basename ( root ) img_resize . save ( os . path . join ( dst_dir , basename + '_half' + ext )) Since image files can have various extensions, it is difficult to specify all of them. With exception handling files = glob . glob ( './data/temp/images/*' ) for f in files : try : img = Image . open ( f ) img_resize = img . resize (( img . width // 2 , img . height // 2 )) root , ext = os . path . splitext ( f ) basename = os . path . basename ( root ) img_resize . save ( os . path . join ( dst_dir , basename + '_half' + ext )) except OSError as e : pass All files that can be opened with Pillow's Image.open() are resized. The approach that explicitly checks the conditions, like in the first example, is called "LBYL: Look Before You Leap", while the approach that uses exception handling, like in the second example, is called "EAFP: Easier to Ask for Forgiveness than Permission". Duck typing with hasattr() and abstract base class in Python Both approaches have pros and cons, but using exception handling can make the code more concise when dealing with processes that involve many conditions.
Markdown
[note.nkmk.me](https://note.nkmk.me/en/) 1. [Home](https://note.nkmk.me/en/) 2. [Python](https://note.nkmk.me/en/python/) # Try, except, else, finally in Python (Exception handling) Modified: 2023-08-15 \| Tags: [Python](https://note.nkmk.me/en/python/), [Error handling](https://note.nkmk.me/en/error-handling/) In Python, `try` and `except` are used to handle exceptions. Additionally, `else` and `finally` can be used to define actions to take at the end of the try-except process. - [8\. Errors and Exceptions - Handling Exceptions — Python 3.11.3 documentation](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) - [8\. Compound statements - The try statement — Python 3.11.3 documentation](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement) Contents - [Basic exception handling in Python: `try ... except ...`](https://note.nkmk.me/en/python-try-except-else-finally/#basic-exception-handling-in-python-try-except) - [Catch a specific exception](https://note.nkmk.me/en/python-try-except-else-finally/#catch-a-specific-exception) - [Store the exception object](https://note.nkmk.me/en/python-try-except-else-finally/#store-the-exception-object) - [Work with base classes](https://note.nkmk.me/en/python-try-except-else-finally/#work-with-base-classes) - [Flow when an exception occurs](https://note.nkmk.me/en/python-try-except-else-finally/#flow-when-an-exception-occurs) - [Catch multiple exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#catch-multiple-exceptions) - [Apply different operations to multiple exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#apply-different-operations-to-multiple-exceptions) - [Apply the same operation to multiple exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#apply-the-same-operation-to-multiple-exceptions) - [Catch all exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#catch-all-exceptions) - [Wildcard except (Bare except)](https://note.nkmk.me/en/python-try-except-else-finally/#wildcard-except-bare-except) - [Base class: `Exception`](https://note.nkmk.me/en/python-try-except-else-finally/#base-class-exception) - [Execute action if no exception occurs: `try ... except ... else ...`](https://note.nkmk.me/en/python-try-except-else-finally/#execute-action-if-no-exception-occurs-try-except-else) - [Clean-up action: `try ... except ... finally ...`](https://note.nkmk.me/en/python-try-except-else-finally/#clean-up-action-try-except-finally) - [Ignore exceptions: `pass`](https://note.nkmk.me/en/python-try-except-else-finally/#ignore-exceptions-pass) - [Practical example: Reading image files](https://note.nkmk.me/en/python-try-except-else-finally/#practical-example-reading-image-files) - [Without exception handling](https://note.nkmk.me/en/python-try-except-else-finally/#without-exception-handling) - [With exception handling](https://note.nkmk.me/en/python-try-except-else-finally/#with-exception-handling) You can also set up debugging assertions with the `assert` statement. - [The assert statement in Python](https://note.nkmk.me/en/python-assert-usage/) ## Basic exception handling in Python: `try ... except ...` ### Catch a specific exception For example, when attempting division by zero, a `ZeroDivisionError` is raised, causing the process to end. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L1-L2) To catch this exception, use `try` and `except` as follows: ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L4-L8) ### Store the exception object By using `except <exception-name> as <variable-name>:`, the exception object is stored in the variable. You can choose any name for the variable, but names like `e` and `err` are commonly used. The exception object contains error messages that are displayed when an exception occurs, allowing you to check the error details by outputting them. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L10-L16) In Python 2, it should be written as `except <exception-name>, <variable-name>:`. ### Work with base classes You can also specify a base class. For example, `ArithmeticError` is the base class for `ZeroDivisionError`. The variable stores the exception object of the derived class that actually occurred. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L18-L27) Check the official documentation for built-in exceptions in Python. - [Built-in Exceptions — Python 3.11.4 documentation](https://docs.python.org/3/library/exceptions.html) ### Flow when an exception occurs When an exception occurs in the `try` clause, the subsequent code in the `try` clause is skipped. For example, if an exception occurs in the middle of the `for` loop, the loop ends at that point, and the code in the `except` clause is executed. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L29-L36) You can specify the code to execute after the `except` clause using the `else` and `finally` clauses, which will be described later. ## Catch multiple exceptions Define the following function that catches `ZeroDivisionError`. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L38-L42) This function can catch `ZeroDivisionError`, but it cannot catch other exceptions. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L44-L48) ### Apply different operations to multiple exceptions You can use multiple `except` clauses to handle different exceptions with different operations. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L50-L62) ### Apply the same operation to multiple exceptions You can specify multiple exception names in a single `except` clause by using a `tuple`. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L64-L74) ## Catch all exceptions You can also catch all exceptions without specifying them. ### Wildcard except (Bare except) All exceptions can be caught by omitting the exception name from the `except` clause. If there are multiple `except` clauses, the exception name can be omitted only in the last `except` clause. The use of an `except` clause without specifying the exception name is referred to as a wildcard except or bare except, and as mentioned in the official documentation, caution should be exercised when using it. > The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! [8\. Errors and Exceptions - Handling Exceptions — Python 3.9.0 documentation](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L76-L86) Using a wildcard except, you can catch all exceptions, including `SystemExit` (raised by `sys.exit()`, etc.) and `KeyboardInterrupt` (triggered by pressing `Ctrl + C`). However, it's often preferable not to catch these particular exceptions. In such cases, using `Exception` instead may be a better option, as described next. ### Base class: `Exception` You can specify `Exception` in the `except` clause, which is the base class for all built-in, non-system-exiting exceptions. - [Built-in Exceptions - Exception — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#Exception) ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L88-L98) The class hierarchy for built-in exceptions is as follows. - [Built-in Exceptions - Exception hierarchy — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#exception-hierarchy) ``` ``` Since `SystemExit` and `KeyboardInterrupt` do not inherit from `Exception`, using `Exception` in the `except` clause will not catch `sys.exit()` or interrupts like `Ctrl + C`. - [Built-in Exceptions - SystemExit — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#SystemExit) - [Built-in Exceptions - KeyboardInterrupt — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt) The base class for all built-in exceptions, including `SystemExit` and `KeyboardInterrupt`, is `BaseException`. If you specify `BaseException` instead of `Exception` in the `except` clause, all exceptions will be caught. - [Built-in Exceptions - BaseException — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#BaseException) It is better to specify the expected exceptions in the `except` clause as much as possible, because catching an unexpected exception may lead to a bug. ## Execute action if no exception occurs: `try ... except ... else ...` You can use the `else` clause to specify an action to be executed if no exception occurs. If an exception does occur and is caught by an `except` clause, the action in the `else` clause will not be executed. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L100-L113) ## Clean-up action: `try ... except ... finally ...` In the `finally` clause, you can specify the clean-up action to be executed whether an exception occurs or not. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L115-L129) You can also use the `else` and `finally` clause together. If no exception occurs, the `else` clause is executed and then the `finally` clause is executed. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L131-L148) ## Ignore exceptions: `pass` If you want to catch an exception and continue without taking any action, use `pass`. ``` ``` source: [exception\_handling.py](https://github.com/nkmk/python-snippets/blob/32f649941860bc4d7e00bb0da76e978639dc53a4/notebook/exception_handling.py#L150-L156) See the following article for details on the `pass` statement. - [The pass statement in Python](https://note.nkmk.me/en/python-pass-usage/) ## Practical example: Reading image files A convenient example of using exception handling is reading image files. The following is an example of resizing image files in a folder using Pillow. - [Resize images with Python, Pillow](https://note.nkmk.me/en/python-pillow-image-resize/) ### Without exception handling Get all file paths in the folder with `glob()` and resize only files that match specific extensions. - [How to use glob() in Python](https://note.nkmk.me/en/python-glob-usage/) - [Get the filename, directory, extension from a path string in Python](https://note.nkmk.me/en/python-os-basename-dirname-split-splitext/) - [The in operator in Python (for list, string, dictionary, etc.)](https://note.nkmk.me/en/python-in-basic/) ``` ``` source: [pillow\_image\_resize\_all.py](https://github.com/nkmk/python-snippets/blob/a3c261dee61e4bd3201478477389813a8aa1ed82/notebook/pillow_image_resize_all.py#L1-L6) ``` ``` source: [pillow\_image\_resize\_all.py](https://github.com/nkmk/python-snippets/blob/a3c261dee61e4bd3201478477389813a8aa1ed82/notebook/pillow_image_resize_all.py#L17-L25) Since image files can have various extensions, it is difficult to specify all of them. ### With exception handling ``` ``` source: [pillow\_image\_resize\_all.py](https://github.com/nkmk/python-snippets/blob/a3c261dee61e4bd3201478477389813a8aa1ed82/notebook/pillow_image_resize_all.py#L27-L37) All files that can be opened with Pillow's `Image.open()` are resized. The approach that explicitly checks the conditions, like in the first example, is called "LBYL: Look Before You Leap", while the approach that uses exception handling, like in the second example, is called "EAFP: Easier to Ask for Forgiveness than Permission". - [Duck typing with hasattr() and abstract base class in Python](https://note.nkmk.me/en/python-duck-typing-hasattr-abc/) Both approaches have pros and cons, but using exception handling can make the code more concise when dealing with processes that involve many conditions. ## Related Categories - [Python](https://note.nkmk.me/en/python/) - [Error handling](https://note.nkmk.me/en/error-handling/) ## Related Articles - [The assert Statement in Python](https://note.nkmk.me/en/python-assert-usage/) - [How to fix "ValueError: The truth value ... is ambiguous" in NumPy, pandas](https://note.nkmk.me/en/python-numpy-pandas-value-error-ambiguous/) - [How to Ignore Warnings in Python](https://note.nkmk.me/en/python-warnings-ignore-warning/) - [pandas: How to fix SettingWithCopyWarning: A value is trying to be set on ...](https://note.nkmk.me/en/python-pandas-setting-with-copy-warning/) - [Measure Execution Time with timeit in Python](https://note.nkmk.me/en/python-timeit-measure/) - [Check the Versions of Python Packages](https://note.nkmk.me/en/python-package-version/) - [pandas: Filter rows/columns by labels with filter()](https://note.nkmk.me/en/python-pandas-filter/) - [Python, Pillow: Flip image](https://note.nkmk.me/en/python-pillow-flip-mirror/) - [Format Strings and Numbers in Python: format()](https://note.nkmk.me/en/python-format-zero-hex/) - [pandas: Remove NaN (missing values) with dropna()](https://note.nkmk.me/en/python-pandas-nan-dropna/) - [Convert between pandas DataFrame/Series and Python list](https://note.nkmk.me/en/python-pandas-list/) - [Sign Function in Python: sign/signum/sgn, copysign](https://note.nkmk.me/en/python-sign-copysign/) - [Concatenate Strings in Python: +, +=, join(), and more](https://note.nkmk.me/en/python-string-concat/) - [How to Start enumerate() at 1 in Python](https://note.nkmk.me/en/python-enumerate-start/) - [Convert Between Isoformat String and datetime in Python](https://note.nkmk.me/en/python-datetime-isoformat-fromisoformat/) Search Categories - [Python](https://note.nkmk.me/en/python/) - [NumPy](https://note.nkmk.me/en/numpy/) - [OpenCV](https://note.nkmk.me/en/opencv/) - [pandas](https://note.nkmk.me/en/pandas/) - [Pillow](https://note.nkmk.me/en/pillow/) - [pip](https://note.nkmk.me/en/pip/) - [scikit-image](https://note.nkmk.me/en/scikit-image/) - [uv](https://note.nkmk.me/en/uv/) - [Git](https://note.nkmk.me/en/git/) - [Jupyter Notebook](https://note.nkmk.me/en/jupyter-notebook/) - [Mac](https://note.nkmk.me/en/mac/) - [Windows](https://note.nkmk.me/en/windows/) - [Image Processing](https://note.nkmk.me/en/image-processing/) - [File](https://note.nkmk.me/en/file/) - [CSV](https://note.nkmk.me/en/csv/) - [JSON](https://note.nkmk.me/en/json/) - [PDF](https://note.nkmk.me/en/pdf/) - [Date and time](https://note.nkmk.me/en/date-and-time/) - [String](https://note.nkmk.me/en/string/) - [Regex](https://note.nkmk.me/en/regex/) - [Numeric](https://note.nkmk.me/en/numeric/) - [Dictionary](https://note.nkmk.me/en/dictionary/) - [List](https://note.nkmk.me/en/list/) - [Error handling](https://note.nkmk.me/en/error-handling/) - [Mathematics](https://note.nkmk.me/en/mathematics/) - [Summary](https://note.nkmk.me/en/summary/) About - GitHub: [nkmk](https://github.com/nkmk) Related Articles - [The assert Statement in Python](https://note.nkmk.me/en/python-assert-usage/) - [How to fix "ValueError: The truth value ... is ambiguous" in NumPy, pandas](https://note.nkmk.me/en/python-numpy-pandas-value-error-ambiguous/) - [How to Ignore Warnings in Python](https://note.nkmk.me/en/python-warnings-ignore-warning/) - [pandas: How to fix SettingWithCopyWarning: A value is trying to be set on ...](https://note.nkmk.me/en/python-pandas-setting-with-copy-warning/) - [Measure Execution Time with timeit in Python](https://note.nkmk.me/en/python-timeit-measure/) - English / [Japanese](https://note.nkmk.me/) - \| - [Disclaimer](https://note.nkmk.me/en/disclaimer/) - [Privacy policy](https://note.nkmk.me/en/privacy-policy/) - [GitHub](https://github.com/nkmk) - ©[nkmk.me](https://nkmk.me/)
Readable Markdown
In Python, `try` and `except` are used to handle exceptions. Additionally, `else` and `finally` can be used to define actions to take at the end of the try-except process. - [8\. Errors and Exceptions - Handling Exceptions — Python 3.11.3 documentation](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) - [8\. Compound statements - The try statement — Python 3.11.3 documentation](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement) Contents - [Basic exception handling in Python: `try ... except ...`](https://note.nkmk.me/en/python-try-except-else-finally/#basic-exception-handling-in-python-try-except) - [Catch a specific exception](https://note.nkmk.me/en/python-try-except-else-finally/#catch-a-specific-exception) - [Store the exception object](https://note.nkmk.me/en/python-try-except-else-finally/#store-the-exception-object) - [Work with base classes](https://note.nkmk.me/en/python-try-except-else-finally/#work-with-base-classes) - [Flow when an exception occurs](https://note.nkmk.me/en/python-try-except-else-finally/#flow-when-an-exception-occurs) - [Catch multiple exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#catch-multiple-exceptions) - [Apply different operations to multiple exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#apply-different-operations-to-multiple-exceptions) - [Apply the same operation to multiple exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#apply-the-same-operation-to-multiple-exceptions) - [Catch all exceptions](https://note.nkmk.me/en/python-try-except-else-finally/#catch-all-exceptions) - [Wildcard except (Bare except)](https://note.nkmk.me/en/python-try-except-else-finally/#wildcard-except-bare-except) - [Base class: `Exception`](https://note.nkmk.me/en/python-try-except-else-finally/#base-class-exception) - [Execute action if no exception occurs: `try ... except ... else ...`](https://note.nkmk.me/en/python-try-except-else-finally/#execute-action-if-no-exception-occurs-try-except-else) - [Clean-up action: `try ... except ... finally ...`](https://note.nkmk.me/en/python-try-except-else-finally/#clean-up-action-try-except-finally) - [Ignore exceptions: `pass`](https://note.nkmk.me/en/python-try-except-else-finally/#ignore-exceptions-pass) - [Practical example: Reading image files](https://note.nkmk.me/en/python-try-except-else-finally/#practical-example-reading-image-files) - [Without exception handling](https://note.nkmk.me/en/python-try-except-else-finally/#without-exception-handling) - [With exception handling](https://note.nkmk.me/en/python-try-except-else-finally/#with-exception-handling) You can also set up debugging assertions with the `assert` statement. - [The assert statement in Python](https://note.nkmk.me/en/python-assert-usage/) ## Basic exception handling in Python: `try ... except ...` ### Catch a specific exception For example, when attempting division by zero, a `ZeroDivisionError` is raised, causing the process to end. ``` ``` To catch this exception, use `try` and `except` as follows: ``` ``` ### Store the exception object By using `except <exception-name> as <variable-name>:`, the exception object is stored in the variable. You can choose any name for the variable, but names like `e` and `err` are commonly used. The exception object contains error messages that are displayed when an exception occurs, allowing you to check the error details by outputting them. ``` ``` In Python 2, it should be written as `except <exception-name>, <variable-name>:`. ### Work with base classes You can also specify a base class. For example, `ArithmeticError` is the base class for `ZeroDivisionError`. The variable stores the exception object of the derived class that actually occurred. ``` ``` Check the official documentation for built-in exceptions in Python. - [Built-in Exceptions — Python 3.11.4 documentation](https://docs.python.org/3/library/exceptions.html) ### Flow when an exception occurs When an exception occurs in the `try` clause, the subsequent code in the `try` clause is skipped. For example, if an exception occurs in the middle of the `for` loop, the loop ends at that point, and the code in the `except` clause is executed. ``` ``` You can specify the code to execute after the `except` clause using the `else` and `finally` clauses, which will be described later. ## Catch multiple exceptions Define the following function that catches `ZeroDivisionError`. ``` ``` This function can catch `ZeroDivisionError`, but it cannot catch other exceptions. ``` ``` ### Apply different operations to multiple exceptions You can use multiple `except` clauses to handle different exceptions with different operations. ``` ``` ### Apply the same operation to multiple exceptions You can specify multiple exception names in a single `except` clause by using a `tuple`. ``` ``` ## Catch all exceptions You can also catch all exceptions without specifying them. ### Wildcard except (Bare except) All exceptions can be caught by omitting the exception name from the `except` clause. If there are multiple `except` clauses, the exception name can be omitted only in the last `except` clause. The use of an `except` clause without specifying the exception name is referred to as a wildcard except or bare except, and as mentioned in the official documentation, caution should be exercised when using it. > The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! [8\. Errors and Exceptions - Handling Exceptions — Python 3.9.0 documentation](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) ``` ``` Using a wildcard except, you can catch all exceptions, including `SystemExit` (raised by `sys.exit()`, etc.) and `KeyboardInterrupt` (triggered by pressing `Ctrl + C`). However, it's often preferable not to catch these particular exceptions. In such cases, using `Exception` instead may be a better option, as described next. ### Base class: `Exception` You can specify `Exception` in the `except` clause, which is the base class for all built-in, non-system-exiting exceptions. - [Built-in Exceptions - Exception — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#Exception) ``` ``` The class hierarchy for built-in exceptions is as follows. - [Built-in Exceptions - Exception hierarchy — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#exception-hierarchy) ``` ``` Since `SystemExit` and `KeyboardInterrupt` do not inherit from `Exception`, using `Exception` in the `except` clause will not catch `sys.exit()` or interrupts like `Ctrl + C`. - [Built-in Exceptions - SystemExit — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#SystemExit) - [Built-in Exceptions - KeyboardInterrupt — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt) The base class for all built-in exceptions, including `SystemExit` and `KeyboardInterrupt`, is `BaseException`. If you specify `BaseException` instead of `Exception` in the `except` clause, all exceptions will be caught. - [Built-in Exceptions - BaseException — Python 3.11.3 documentation](https://docs.python.org/3/library/exceptions.html#BaseException) It is better to specify the expected exceptions in the `except` clause as much as possible, because catching an unexpected exception may lead to a bug. ## Execute action if no exception occurs: `try ... except ... else ...` You can use the `else` clause to specify an action to be executed if no exception occurs. If an exception does occur and is caught by an `except` clause, the action in the `else` clause will not be executed. ``` ``` ## Clean-up action: `try ... except ... finally ...` In the `finally` clause, you can specify the clean-up action to be executed whether an exception occurs or not. ``` ``` You can also use the `else` and `finally` clause together. If no exception occurs, the `else` clause is executed and then the `finally` clause is executed. ``` ``` ## Ignore exceptions: `pass` If you want to catch an exception and continue without taking any action, use `pass`. ``` ``` See the following article for details on the `pass` statement. - [The pass statement in Python](https://note.nkmk.me/en/python-pass-usage/) ## Practical example: Reading image files A convenient example of using exception handling is reading image files. The following is an example of resizing image files in a folder using Pillow. - [Resize images with Python, Pillow](https://note.nkmk.me/en/python-pillow-image-resize/) ### Without exception handling Get all file paths in the folder with `glob()` and resize only files that match specific extensions. - [How to use glob() in Python](https://note.nkmk.me/en/python-glob-usage/) - [Get the filename, directory, extension from a path string in Python](https://note.nkmk.me/en/python-os-basename-dirname-split-splitext/) - [The in operator in Python (for list, string, dictionary, etc.)](https://note.nkmk.me/en/python-in-basic/) ``` ``` ``` ``` Since image files can have various extensions, it is difficult to specify all of them. ### With exception handling ``` ``` All files that can be opened with Pillow's `Image.open()` are resized. The approach that explicitly checks the conditions, like in the first example, is called "LBYL: Look Before You Leap", while the approach that uses exception handling, like in the second example, is called "EAFP: Easier to Ask for Forgiveness than Permission". - [Duck typing with hasattr() and abstract base class in Python](https://note.nkmk.me/en/python-duck-typing-hasattr-abc/) Both approaches have pros and cons, but using exception handling can make the code more concise when dealing with processes that involve many conditions.
Shard13 (laksa)
Root Hash14415757146955323613
Unparsed URLme,nkmk!note,/en/python-try-except-else-finally/ s443