Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Catching Multiple Exceptions | Introduction to Exceptions
Python Error Handling

bookChallenge: Catching Multiple Exceptions

Why Catch Multiple Exceptions

When you write Python code that interacts with user input or external data, you must expect things to go wrong. For example, you might ask a user to enter a number as a string, convert it to an integer, and then use it as a divisor. Two common problems can occur:

  • The string cannot be converted to an integer (such as "hello" or "3.14");
  • The integer is zero, causing a division by zero error.

If you do not handle these exceptions, your program will crash and display a confusing error message. By catching multiple exceptions, you can provide clear feedback and keep your program running smoothly.

Scenario: Suppose you ask a user to enter a number as a string, then divide 100 by that value. If the user enters "0", you get a ZeroDivisionError. If the user enters "abc", you get a ValueError. You need to catch both errors and respond with helpful messages.

Catching multiple exceptions in a single block of code makes your programs safer and more user-friendly.

Handling Multiple Exceptions in a Single Try-Except Block

When you expect more than one type of error in a block of code, use multiple except clauses after a single try block. This structure allows you to respond differently depending on which exception occurs, keeping your code organized and easier to read.

try:
    # Code that may raise multiple exceptions
    risky_operation()
except ValueError:
    print("A ValueError occurred.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Key points:

  • Place all code that might raise exceptions inside one try block;
  • Add a separate except clause for each exception type you want to handle;
  • Each except clause only handles its specific exception type, so error messages and recovery steps stay clear and relevant.

This approach makes your code more maintainable and ensures that you provide meaningful feedback for each possible error.

Oppgave

Swipe to start coding

Create a function named safe_divide_from_string that takes two arguments: number_str (a string) and divisor (an integer). The function should:

  • Convert number_str to an integer;
  • Divide 100 by that integer;
  • Handle both ValueError (if the string cannot be converted) and ZeroDivisionError (if division by zero occurs) using try-except;
  • Return the result if successful, or a string message describing the error if an exception is caught.

Løsning

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 4
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Suggested prompts:

Can you show an example with user input handling both exceptions?

What happens if an unexpected exception occurs?

Is it possible to catch multiple exceptions in a single except clause?

close

Awesome!

Completion rate improved to 6.67

bookChallenge: Catching Multiple Exceptions

Sveip for å vise menyen

Why Catch Multiple Exceptions

When you write Python code that interacts with user input or external data, you must expect things to go wrong. For example, you might ask a user to enter a number as a string, convert it to an integer, and then use it as a divisor. Two common problems can occur:

  • The string cannot be converted to an integer (such as "hello" or "3.14");
  • The integer is zero, causing a division by zero error.

If you do not handle these exceptions, your program will crash and display a confusing error message. By catching multiple exceptions, you can provide clear feedback and keep your program running smoothly.

Scenario: Suppose you ask a user to enter a number as a string, then divide 100 by that value. If the user enters "0", you get a ZeroDivisionError. If the user enters "abc", you get a ValueError. You need to catch both errors and respond with helpful messages.

Catching multiple exceptions in a single block of code makes your programs safer and more user-friendly.

Handling Multiple Exceptions in a Single Try-Except Block

When you expect more than one type of error in a block of code, use multiple except clauses after a single try block. This structure allows you to respond differently depending on which exception occurs, keeping your code organized and easier to read.

try:
    # Code that may raise multiple exceptions
    risky_operation()
except ValueError:
    print("A ValueError occurred.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Key points:

  • Place all code that might raise exceptions inside one try block;
  • Add a separate except clause for each exception type you want to handle;
  • Each except clause only handles its specific exception type, so error messages and recovery steps stay clear and relevant.

This approach makes your code more maintainable and ensures that you provide meaningful feedback for each possible error.

Oppgave

Swipe to start coding

Create a function named safe_divide_from_string that takes two arguments: number_str (a string) and divisor (an integer). The function should:

  • Convert number_str to an integer;
  • Divide 100 by that integer;
  • Handle both ValueError (if the string cannot be converted) and ZeroDivisionError (if division by zero occurs) using try-except;
  • Return the result if successful, or a string message describing the error if an exception is caught.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 4
single

single

some-alt