Nathan Kirui
Nathan Kirui

Reputation: 69

Handling exception returned by a method

I am calling a method that throws Valuerror exception or returns valid response as a string. I am not able to handle the situation if it is an exception. If the return is the valid string I am supposed to slice it and do other things with it.

x = sanitize("245755487")

try:
   print(data = x[:3])

except:
    print(x)



def sanitize(self,tel):
   data = [d for d in tel if d.isalnum()]   
   digits = int(len(data))   
   if digits < 10:
      raise ValueError("The digit cannot be below 10")
   else:
      "".join(data)

If the x is subscribable I am supposed to get that string sliced.

Upvotes: 1

Views: 29

Answers (1)

Nevus
Nevus

Reputation: 1407

You need to place call to sanitize method in try block because sanitize is the method that raises exception. Placing it outside try block makes no sense. You should handle error in except block instead of print(x).

try:
   x = sanitize("245755487")
   print(data = x[:3])

except ValueError as err:
   print(err);
   #<what would you like to do if there is an error?>

Upvotes: 1

Related Questions