セクション 1. 章 5
single
Challenge: Catching the Negative
メニューを表示するにはスワイプしてください
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.
タスク
スワイプしてコーディングを開始
Define a custom exception class and use it in a function to handle invalid input.
- Define a custom exception class named
NegativeNumberErrorthat inherits fromException. - Implement a function
check_positive_number(num)that raises your custom exception ifnumis less than 0. - The function should return
numunchanged 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".
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 5
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください