我正在通過Python Koans學習Python,並且提出了在Python中引發異常的問題。具體來說,我經歷了koan後甚至與try...except...
混淆。我知道對Rudy Koan Ruby Koan 151 raising exceptions有類似的問題。但我是一個Python新手,對Ruby一無所知。Python Koan 131引發異常
因此,這裏的公案:
# You need to finish implementing triangle() in the file 'triangle.py'
from triangle import *
class AboutTriangleProject2(Koan):
# The first assignment did not talk about how to handle errors.
# Let's handle that part now.
def test_illegal_triangles_throw_exceptions(self):
# Calls triangle(0, 0, 0)
self.assertRaises(TriangleError, triangle, 0, 0, 0)
self.assertRaises(TriangleError, triangle, 3, 4, -5)
self.assertRaises(TriangleError, triangle, 1, 1, 3)
self.assertRaises(TriangleError, triangle, 2, 4, 2)
以下是triangle.py
def triangle(a, b, c):
# DELETE 'PASS' AND WRITE THIS CODE
if a == b and b == c and c == a:
return 'equilateral'
if a == b or b == c or a == c:
return 'isosceles'
else:
return 'scalene'
# Error class used in part 2. No need to change this code.
class TriangleError(StandardError):
pass
我應該完成triangle()
功能。
據我的理解,try...except...
的功能就像是如果滿足某些標準然後做某件事,否則通過例外。那麼在我的情況下,我應該使用if ... then raise TriangleError
還是try... except ...
?他們之間有什麼不同?
非常感謝!