Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Raising | Error Handling
Mastering Python: Annotations, Errors and Environment

book
Raising

Let's learn how to raise an error.

Errors can be raised using the raise keyword:

raise TypeError
1
raise TypeError
copy

The TypeError in the example above was raised without a message.

To output an error message, you can pass a string inside the parentheses () after the error object:

raise ValueError("Wrong value!")
1
raise ValueError("Wrong value!")
copy
Uppgift

Swipe to start coding

You have implemented the perimeter() function that returns the triangle perimeter. This function receives the sides of a triangle (a, b, and c). You need to add error raising to this function.

  1. All received sides should be int or float data type. In another case, the function should raise the TypeError with the message "All sides should be int or float type".

  2. In a triangle, all sides should have a length greater than 0. In other cases, the function should raise the ValueError with the message "All sides should be greater than 0".

  3. In a triangle, the sum of two sides must always be greater than the third side (otherwise, the two sides would not reach each other through the third side). Therefore, if one of the received sides is greater than the sum of the other two, the program must raise the ValueError with the message "It's not a triangle".

Lösning

def perimeter(a, b, c):
if not all([
isinstance(a, (int, float)),
isinstance(b, (int, float)),
isinstance(c, (int, float))
]):
raise TypeError("All sides should be int or float type")
if any([a <= 0, b <= 0, c <= 0]):
raise ValueError("All sides should be greater than 0")
if not (a + b > c and b + c > a and a + c > b):
raise ValueError("It's not a triangle")
return a + b + c

print(perimeter(25, 12, 15))

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 3
def perimeter(a, b, c):
if not all([
isinstance(a, (int, float)),
isinstance(b, (int, float)),
isinstance(c, (int, float))
]):
raise ___("All sides should be int or float type")
if any([a <= 0, b <= 0, c <= 0]):
___ ValueError("___")
if not (a + b > c and b + c > a and a + c > b):
___ ___("___")
return a + b + c

print(perimeter(25, 12, 15))

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt