|
| 1 | +--- |
| 2 | +Title: 'try' |
| 3 | +Description: 'Attempts to execute a block of code and lets the program handle exceptions gracefully if errors occur.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Error Handling' |
| 9 | + - 'Exceptions' |
| 10 | + - 'Python' |
| 11 | + - 'Values' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`try`** keyword in Python is used to define a code block that may raise an exception, allowing errors to be caught and handled gracefully with `except`, and optionally complemented by `else` and `finally` clauses. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +try: |
| 23 | + # Code that might raise an exception |
| 24 | +except ExceptionType: |
| 25 | + # Code to handle the exception |
| 26 | +else: |
| 27 | + # (Optional) Code to run if no exceptions occur |
| 28 | +finally: |
| 29 | + # (Optional) Code that always runs |
| 30 | +``` |
| 31 | + |
| 32 | +In the syntax: |
| 33 | + |
| 34 | +- `except` (Optional): Specifies the type of exception to catch. Multiple `except` blocks can handle different exceptions. |
| 35 | +- `else` (Optional): A block that runs only if the `try` block doesn't raise an exception. |
| 36 | +- `finally` (Optional): A block that always runs, regardless of whether an exception occurred or not. |
| 37 | + |
| 38 | +**Return value:** |
| 39 | + |
| 40 | +The `try` statement itself does not return a value. It controls the flow of execution by handling exceptions within its block. |
| 41 | + |
| 42 | +## Example: Handling Division Error with `try-except` |
| 43 | + |
| 44 | +This example shows how to catch a `ZeroDivisionError` using a simple `try-except` block: |
| 45 | + |
| 46 | +```py |
| 47 | +try: |
| 48 | + x = 10 / 0 |
| 49 | +except ZeroDivisionError: |
| 50 | + print("Cannot divide by zero.") |
| 51 | +``` |
| 52 | + |
| 53 | +The output of this code will be: |
| 54 | + |
| 55 | +```shell |
| 56 | +Cannot divide by zero. |
| 57 | +``` |
| 58 | + |
| 59 | +## Codebyte Example: Handling Multiple Exceptions with `try-except-finally` |
| 60 | + |
| 61 | +This codebyte example captures both invalid input and division-by-zero errors while ensuring a final message always prints: |
| 62 | + |
| 63 | +```codebyte/python |
| 64 | +try: |
| 65 | + number = 5 |
| 66 | + print("Reciprocal is:", 1 / number) |
| 67 | +except ValueError: |
| 68 | + print("That's not a valid number!") |
| 69 | +except ZeroDivisionError: |
| 70 | + print("Cannot divide by zero.") |
| 71 | +finally: |
| 72 | + print("Thanks for trying!") |
| 73 | +``` |
| 74 | + |
| 75 | +> **Note:** Change the value entered for `number` to see different results and exception handling in action. |
0 commit comments