Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Additional Elements | Handling Structure
Error Handling in Python
course content

Kursusindhold

Error Handling in Python

Error Handling in Python

1. Handling Structure
2. Exception Usage

book
Additional Elements

The full handle structure has 2 additional elements: else and finally.

Look at the example:

1234567891011121314151617181920
def divide_numbers(a, b): try: result = a / b except ZeroDivisionError as error: print("(except) ZeroDivisionError: Cannot divide by zero.") except TypeError as error: print("(except) TypeError: Invalid data type for division.") else: print("(else) Division result:", result) finally: print("(finally) Finally block executed.") # Example usage: print("=== CASE 1 ===") divide_numbers(10, 2) # This will execute the else block and finally block. print("=== CASE 2 ===") divide_numbers(5, 0) # This will raise a ZeroDivisionError, execute the except block, and the finally block. print("=== CASE 3 ===") divide_numbers(10, "two") # This will raise a TypeError, execute the except block, and the finally block.
copy

As you can see, the code handles different exceptions appropriately and ensures:

  • the else block is executed when errors are not raised;

  • the finally block is executed in all cases.

Handle Structure Diagram

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 6

Spørg AI

expand
ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

course content

Kursusindhold

Error Handling in Python

Error Handling in Python

1. Handling Structure
2. Exception Usage

book
Additional Elements

The full handle structure has 2 additional elements: else and finally.

Look at the example:

1234567891011121314151617181920
def divide_numbers(a, b): try: result = a / b except ZeroDivisionError as error: print("(except) ZeroDivisionError: Cannot divide by zero.") except TypeError as error: print("(except) TypeError: Invalid data type for division.") else: print("(else) Division result:", result) finally: print("(finally) Finally block executed.") # Example usage: print("=== CASE 1 ===") divide_numbers(10, 2) # This will execute the else block and finally block. print("=== CASE 2 ===") divide_numbers(5, 0) # This will raise a ZeroDivisionError, execute the except block, and the finally block. print("=== CASE 3 ===") divide_numbers(10, "two") # This will raise a TypeError, execute the except block, and the finally block.
copy

As you can see, the code handles different exceptions appropriately and ensures:

  • the else block is executed when errors are not raised;

  • the finally block is executed in all cases.

Handle Structure Diagram

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 6
Vi beklager, at noget gik galt. Hvad skete der?
some-alt