Consider writing a small library in python that has this one simple method x
which accepts an argument ac
& returns the computed value 10/ac
. now the catch here is ac
cannot be 0
. so how do i handle this case in my method.there are these ways that comes to my mind.
NOTE: i have looked into python exception handling but it just shows how to use try except
not the specific problem that i am asking.
method 1
def x(ac):
try:
return (10/ac)
except ZeroDivisionError:
raise ZeroDivisionError("ac cannot be zero")
The above code just uses a plain try except block to catch spcific exceptions and raises the exception to the calling code. so the calling code would look like this:
# some script...
try:
x(0)
except ZeroDivisionError as e:
log(e)
but in this case, i would have to know before hand what all possible exceptions that method x
might raise.
Method 2:
def x(ac):
if ac == 0:
raise ValueError("ac cannot be zero") # or ZeroDivisionError??
else:
return (10/ac)
i guess this is semantically same as previous one except that to check some conditions(that we know might occur) using if's
& raising exceptions based on that.
It also suffers from the same problem of knowing beforehand what exceptions the method might throw.
method 3
The last method is not handling any exception in the library method rather leave it to the client code but this obviously doesn't makes sense as the client would never be able to know why exactly the error might occur while resort to something like
def x(ac):
return (10/ac)
try:
x(20)
except Exception as e:
log(e)
now this method here was a simple method with just one opertaion but what if the method itself is doing something complicated like connecting to the database then fetching some results. something like :
def x(db):
conn = db.connect('localhost')
results = connec.fetch(user_id=2)
return results
if something is unclear please let me know.