Python, distinguishing custom exceptions - python

fairly new to Python here. Have this code:
def someFunction( num ):
if num < 0:
raise Exception("Negative Number!")
elif num > 1000:
raise Exception("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except Exception:
print "This was a negative number but we didn't crash"
except Exception:
print "This was a big number but we didn't crash"
else:
print "All tests passed and we didn't crash"
I originally used raise "Negative Number!" etc but quickly discovered that this was the old way of doing things and you have to call the Exception class. Now it's working fine but how do I distinguish between my two exceptions? For the code below it's printing "This was a negative number but we didn't crash". Any pointers on this would be great. Thanks!

you need to create your own exception classes if you want to be able to distinguish the kind of exception that happened. example (i inherited from ValueError as i think this is the closest to what you want - it also allows you to just catch ValueError should the distinction not matter):
class NegativeError(ValueError):
pass
class BigNumberError(ValueError):
pass
def someFunction( num ):
if num < 0:
raise NegativeError("Negative Number!")
elif num > 1000:
raise BigNumberError("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except NegativeError as e:
print "This was a negative number but we didn't crash"
print e
except BigNumberError as e:
print "This was a big number but we didn't crash"
print e
else:
print "All tests passed and we didn't crash"

Related

Python exception: execute code if a specific exception is raised or else

Let's say I have the following code, that assign 1 and print it in case the value is None or not negative.
value = None
class NegativeNumber(Exception):
pass
class NotFound(Exception):
pass
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
except NotFound:
value = 1
print(value)
else:
value = 1
print(value)
Is there a way to avoid repeat twice to assign value=1 and print it?
It would be ideal something like except NotFound or else, but I have not found anything similar in python.
There is no except ... or else: construct. Suppress the exception inside the try block to trigger the else block for the exception as well:
try:
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NotFound:
pass # suppress exception
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)
Instead of using try/except to suppress the exception, contextlib.suppress can be used instead. This can make the intention clearer, as it explicitly names how the exception is handled.
try:
with suppress(NotFound):
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)

Understanding the ValueError: "Invalid numbers" in python

I have the following question:
Define a function called exce_sum where you return the sum of two arguments
But if both arguments are 0, the function should raise an exception saying "Invalid numbers"
The exception needs to have the ValueError() class and the return type of the exception must be a string.
Use try and except.
I wrote the following code:
def exce_sum(x,y):
if x==0 and y==0:
raise ValueError("Invalid numbers")
try:
z=x+y
return(z)
except:
return("the return type of the exception must be a string")
When I write the function exce_sum(0,0)
I receive the error ValueError: Invalid numbers and not ValueError: "Invalid numbers".
However, I do not know how to receive the error ValueError: "Invalid numbers".
Thank you in advance for your help
Change this to
if x==0 and y==0:
raise ValueError("Invalid numbers")
this
if x==0 and y==0:
raise ValueError('"Invalid numbers"')
I don't think you are supposed to print the double quotes anyway :) When exceptions are printed out to console, the message is typically not enclosed in double quotes.
The following should do the trick (you had an unnecessary try-except block):
def exce_sum(x, y):
if x == 0 and y == 0:
raise ValueError("Invalid numbers") # if you still want the quotes use '"Invalid numbers"'
z = x + y
return str(z)
Solution for your questions could be
def exce_sum(num1,num2):
try:
if (num1 == 0 and num2 == 0):
raise ValueError("Invalid Numbers")
else:
return num1 + num2
except ValueError as error:
print(error)
exce_sum(0,0)

Conditional except statements in Python

Is there a way to make an except statement conditional - in other words, only catch a type of exception if the condition is true? This is the idea I have, but it seems like it won't work
try:
<code>
if condition == True:
except Exception as e:
<error handling>
No, you can't do that. What you can do is catch the error then check the condition inside the except block and re-raise if necessary:
except Exception as e:
if not condition:
raise
Not like that, but I find this to be the cleanest solution
try:
<code>
except Exception as e:
if condition:
<error handling>
else:
raise # re raises the exception
You could use different exceptions for each case and catch them seperately:
import random
class myException_1(Exception):
pass
class myException_2(Exception):
pass
try:
a = random.randint(0,10)
if a % 2 == 0:
raise myException_1("something happened")
elif a % 3 ==0:
raise myException_2("something else happened")
else:
print("we made it!")
except myException_2 as e:
print("a was divisible by 3")
print(e)
except myException_1 as e:
print("a was divisible by 2")
print(e)

Exception Handling by validating simple inputs

I am new to Python, after I managed to learn Java at an advanced level.
In Java input validation with exception handling was never a problem to me but somehow in python i get a little confused:
Here an example of a simple FizzBuzz programm which can only read numbers in between 0 and 99, if otherwise, an exception has to be thrown:
if __name__ == '__main__':
def fizzbuzz(n):
try:
if(0<= n <= 99):
for i in range(n):
if i==0:
print("0")
elif (i%3==0 and i%7==0) :
print("fizzbuzz")
elif i%3==0:
print("fizz")
elif i%7==0:
print("buzz")
else:
print(i)
except Exception:
print("/// ATTENTION:The number you entered was not in between 0 and 99///")
try:
enteredNumber = int(input("Please enter a number in between 0 and 99: "))
fizzbuzz(enteredNumber)
except Exception:
print("/// ATTENTION: Something went wrong here. Next time, try to enter a valid Integer ////")
If i run that and enter e.g. 123 the code just terminates and nothing happens.
You need to raise an exception from fizzbuzz() when your condition is not met. Try below:
if __name__ == '__main__':
def fizzbuzz(n):
try:
if(0<= n <= 99):
for i in range(n):
if i==0:
print("0")
elif (i%3==0 and i%7==0) :
print("fizzbuzz")
elif i%3==0:
print("fizz")
elif i%7==0:
print("buzz")
else:
print(i)
else:
raise ValueError("Your exception message")
except Exception:
print("/// ATTENTION:The number you entered was not in between 0 and 99///")
try:
enteredNumber = int(input("Please enter a number in between 0 and 99: "))
fizzbuzz(enteredNumber)
except Exception:
print("/// ATTENTION: Something went wrong here. Next time, try to enter a valid Integer ////")
Also, you must catch specific exceptions instead of catching the generic exception.
If you want to catch an exception you need to make sure it will get raised if the desired scenario occurs.
Since the code block between try and except does not raise an exception by itself, you need to raise one by yourself:
try:
if(0<= n <= 99):
...
else:
raise Exception()
except Exception:
...

Python Issue: Try and Excepts with if

This is probably very basic but I am trying to trigger the Except to run if cointype() is not within the dictionary coin_int but it jumps straight out of the if condition without using the Except even if a value error is met?
Thanks for any help.
try:
coin_type = input("Input your coin: 1p, 2p, 5p etc... ")
if coin_type in coin_int:
print("That value is recognised inside the list of known coin types")
except ValueError:
print("That value of coin is not accepted, restarting...")
you want to raise an exception. Just
raise ValueError("wrong coin type")
Firstly your except will never be reached... you don't "try" anything that will raise ValueError exception... Let me first show how to this, and then basically say that in this case you don't gain anything by using try/except:
coin_int = ("1p", "2p", "5p")
while True:
coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
try:
coin_int.index(coin_type)
print("value accepted, continuouing...")
break
except ValueError:
print("That value of coin is not accepted, try again and choose from", coin_int)
But this is equivalent and in this case just as efficient (if not better actually both in performance and readability):
coin_int = ("1p", "2p", "5p")
while True:
coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
if coin_type in coin_int:
print("value accepted, continuouing...")
break
else:
print("That value of coin is not accepted, try again and choose from", coin_int)
If you really want to stop program execution then do any of the following in the except:
raise to raise the excception caught with default message
raise ValueError("That value of coin is not accepted, try again and choose from", coin_int) which also can be used in the else to raise the specific exception with custom message
Your program should looks like this. (i am giving example through a list instead of dictionary)
coin_int = ['1p', '2p', '3p', '4p', '5p']
try:
coin_type = '6p'
if coin_type in coin_int:
print("That value is recognised inside the list of known coin types")
else:
raise ValueError("wrong coin type")
except ValueError as error:
print("That value of coin is not accepted, restarting..." + repr(error))

Categories

Resources