Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class exceptions
#1
Hi,
Question without code, I'm looking for best practice.
Simplified: a program imports a class "sphere.py".
In sphere.py, 3 functions: Circonf(), Volume(), surface()
These calculations are called with the diameter as an argument.
ball = sphere(5)
v= ball.Volume() ....
Question:
What if sphere is called with a wrong argument (negative or string or zero...),
it generates an error in the class, but how will the main program know?
-
Should I simply put a try-except in the class and return some error code?
Or is there a more appropriate solution to this problem.
thx,
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#2
I think the best solution is to raise an exception when there is an error. This leaves client code free to catch the exception or to let it propagate or to ensure that the argument is always correct. So I suggest
class Sphere:
    def __init__(self, radius):
        if radius < 0:
            raise ValueError('Non negative radius expected, got', radius)
        ...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PiCamera - print exceptions? korenron 2 843 Dec-15-2022, 10:48 PM
Last Post: Larz60+
  is this a good way to catch exceptions? korenron 14 4,734 Jul-05-2021, 06:20 PM
Last Post: hussaind
  Python, exceptions KingKhan248 6 3,057 Nov-15-2020, 06:54 AM
Last Post: buran
  Split string between two different delimiters, with exceptions DreamingInsanity 2 2,050 Aug-24-2020, 08:23 AM
Last Post: DreamingInsanity
  handling 2 exceptions at once Skaperen 2 2,321 Jun-27-2020, 08:55 AM
Last Post: Yoriz
  remove spaces with exceptions catosp 4 2,425 May-29-2020, 09:32 AM
Last Post: catosp
  Looking for advice and Guidance on Exceptions used within Functions paul41 1 2,165 Nov-14-2019, 12:33 AM
Last Post: Larz60+
  multi-line messages in raised exceptions? Skaperen 3 7,362 Aug-01-2019, 02:17 AM
Last Post: Skaperen
  Creating custom exceptions that co-operate LadySvetlana 4 3,084 Mar-19-2019, 04:24 PM
Last Post: LadySvetlana
  Problems with not having exceptions crash my script league55 7 4,903 Feb-16-2018, 09:06 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020