Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Challenge: Catching the Negative | Comprehensive Error Handling (Exceptions)
Python Structural Programming
Abschnitt 1. Kapitel 5
single

single

Challenge: Catching the Negative

Swipe um das Menü anzuzeigen

Custom exceptions let you define error types that describe specific problems in your code. In Python, create a custom exception by subclassing Exception. Raise your exception with raise when a certain condition is met, and handle it using a try-except block.

Aufgabe

Wischen, um mit dem Codieren zu beginnen

Define a custom exception class and use it in a function to handle invalid input.

  • Define a custom exception class named NegativeNumberError that inherits from Exception.
  • Implement a function check_positive_number(num) that raises your custom exception if num is less than 0.
  • The function should return num unchanged if it is 0 or positive.
  • Use print statements to display the result of calling your function with both valid and invalid input.
  • If an exception is raised, catch it and print the exception message "Number must be non-negative".

Lösung

Switch to desktopWechseln Sie zum Desktop, um in der realen Welt zu übenFahren Sie dort fort, wo Sie sind, indem Sie eine der folgenden Optionen verwenden
War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 5
single

single

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

some-alt