How continue execute program after assertion in python? - python

I am learning Exception in python and i have some doubt:
Can we use any name as error in raise?
like i have read when you use raise you have to define error type so can't i use any stringname as Error? like SkienaError or i have to keep in mind all the error types and have to use only those Error type names ?
a=int(input())
if a!=10:
raise SkienaError
else:
print(a,"pp")
Second doubt is suppose i want user should input int but he input string so an assert pop up but i want program should continue without terminate and again ask for input until user give int type input , I don't want to use while loop here i want to know if it is possible with raise or assert in python ? like:
a=int(input())
assert type(a)==int
print(a,"hello")
So if user give str type input then is it possible program keep giving error and asking new input until input type is int.

In order to make your own exception, you'll have to create it.
e.g.
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
To continue execution after a thrown Exception, do it like this:
a = 5
try:
assert a == 5
except AssertionError as e:
print(e)
A try block will attempt to execute a block of code. If an exception occurs, it will execute the except block.

This might also work for your situation. The function Assert() prints a message sTxt in red color, if the Boolean input bCond is False and interpreter continues execution:
RED, END = '\033[91m', '\033[0m'
printRed = lambda sTxt: print(RED + sTxt + END)
Assert = lambda bCond=False, sTxt='': printRed(sTxt) if not bCond else None

Related

Python Raising an Exception within "try" block, then catching the same Exception

Came across try/except blocks, such as:
def foo(name):
try:
if name == "bad_name":
raise Exception()
except Exception:
do_something()
return
Is there a reason for doing this, instead of:
def foo(name):
if name == "bad_name":
do_something()
return
In your example specific I would also not have used try/except because as you stated, you could just use an if statement.
Try/except is for occasions where you know the program may crash, so therefore you have written some code that'll run instead of the entire program crashing. You could for example override the default error messages with custom ones.
A better example could be that you want to multiply a number the user wrote times two. Since the input function always returns a string, we need to cast it to an int using the built-in int function. This would work fine if the user had typed in an integer, but if the user had typed in a str instead, the entire program would crash. Let's say we want to print out a message if that happens, we could use try/except. If we also want to repeat the question over and over again until the user writes an integer, we can use a simple while loop. The code below is an implementation of this.
print("Write any integer and I will multiply it with two!")
while True:
# Get user input
userInput = input("Write any number: ")
try:
# Here we try to cast str to int
num = int(userInput)
# The next line will only be run if the line before
# didn't crash. We break out of the while loop
break
# If the casting didn't work, this code will run
# Notice that we store the exception as e,
# so if we want we could print it
except Exception as e:
print("{} is not an integer!\n".format(userInput))
# This code will be run if the while loop
# is broken out of, which will only happen
# if the user wrote an integer
print("Your number multiplied with 2:\n{}".format(num * 2))
Expected outcome:
Write any integer and I will multiply it with two!
Write any number: a
a is not an integer!
Write any number: b
b is not an integer!
Write any number: 4
Your number multiplied with 2:
8

Does a try except stop right away in python if an exception is found?

If I have a try except block in my python code, and the first line of my try statement raises an exception will it automatically move on to exception or will it finish the try block first?
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
Here is it checking if it can int(string), which it can't, and then it immediately moves onto except, or does it do the string assignment first?
When I run it, it seems like it stops right away, but I want to know if that's happening for sure or something else.
Thanks
Let's try it.
try:
1/0
print("what?")
except:
print("nope")
Output:
nope
>>>
When an exception is raised it moves on to the except.
From the python docs, I found this,
"The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above."
Cheers!
Hope it helps!
#the try block is to run the process
try:
string = "This was a mistake, can't int string"
#you are parsing the string into an int
int(string)
#this block is to capture the exception when it is raised
except:
#here I am just printing the exception
print('Exception')
#the pass is to pass the execution and follow the remaining process.
pass
Output:
Exception
>>>
Well, that the whole point of an error handler. When an error occurs in out program, it crashes, it won't simply skip the error line.
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
So if the try block finishes even after an error occurred in the middle, then the error handler'd seem a bit pointless.
There seem to be some issue with your program and maybe your understanding of the try except block.
First of all, from the block of code you have provided, it seems to me like string isn't even defined yet when you try to pass int(string).
Secondly, the string variable which you seem to be defining under seems to me like is something you are trying to print to the console once the program spits out an error and passes to the except block. If this is what you are trying to do, then your code should look something like this:
try:
int(string)
except:
print("This was a mistake, can't int string")
If you were to run the code provided above, you would indeed confirm that the try except statement is working as it would print "This was a mistake, can't int string" into the console instead of giving an error. Hope this was somewhat helpful and understandable. You got this chief, keep grinding!

Where should I print my output at this simple exception handling?(Python)

Hello guys is there any differences between print my output in "try" clause or putting it after "except" clause with "else:"?
here is the code:
try:
Value1 = int(input("Type the first number: "))
Value2 = int(input("Type the second number: "))
Output = Value1 / Value2
except ZeroDivisionError:
print("Attempted to divide by zero!")
else:
print(Output)
or this?
try:
Value1 = int(input("Type the first number: "))
Value2 = int(input("Type the second number: "))
Output = Value1 / Value2
print(Output)
except ZeroDivisionError:
print("Attempted to divide by zero!")
I mean which one is better? because the result is same.
Thanks.
Like you already know we are talking about error handling when we are using try...except.
When an error is generated by an operation (or other statements) Python will stop the try block execution and is passed down to the first except block that matches the raised exception.
In case there isn't an except clause that matches our exception, it is passed on the outer try statement. This until it's handled or no handler is found, the raised exception becomes an unhandled exception and execution stops with a message of the error traceback.
In addition to except block we can use a finally block, that will be executed regardless of whether an exception occurs, and else block. The last one is useful for code that must be executed if the try clause does not raise an exception.
Your examples
How you said this two pieces of code gives the same result. However, with we read on documentation page of Python we have this affirmation:
"The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement."
Simple speaking if you have different statements that raises the same error, but for one them you aren't interested in catching it, move it to else clause. Look on this question on stack to understand better.
So in your case you can let print statement in try block because you will not catch some particular exceptions from it and there isn't much difference in this case where you put the print statement. However, I think the second example is a good logic separation of type "If no errors where founded then let's execute print".
The else clause is run only when no exception is thrown.
So the reason why you'd want to put it in there is to make it explicit: you only want to print the output if there was no exception.
As you mentioned, in your code, there's no functional difference to what happens.
See the docs for more information.
The first one will work fine as per your expectations (assuming that you don't want to bring up the python error prompt and halt the program).
It simply prescribes that IF 2nd digit is zero then it won't print the Python error prompt and pass it to the print command (And that's how it should be). Otherwise, in every other case, no matter whatever the divisor is, it will always give an output, so that way you eliminate nearly all loopholes.
Suggestion:
Keep the input type as float instead of int, that way you'll be able to print the division for decimal numbers input also. Ex-2/3

How to return a value and raise an Exception

I have two objectives with this try/except statement.
It needs to return a value of 1 if no problems occurred, or 0 if any problems occurred.
It needs to raise an exception and end the script.
I have the return value working. I also have the SystemExit() working. But together, they aren't working.
My Python Script (that's relevant):
except IOError:
value_to_return = 0
return value_to_return
raise SystemExit("FOOBAR")
With this, it ignores the raise SystemExit("FOOBAR") line completely. How do I go about getting a returned value and still raise SystemExit("FOOBAR")? This may be elementary to some, but I'm actually having quite a bit of difficulty with it.
Returning and raising are mutually exclusive.
Raising SystemExit will end the script. A few cleanup routines get to run, and if the caller really, really wants to, they can catch the SystemExit and cancel it, but mostly, you can think of it as stopping execution right there. The caller will never get a chance to see a return value or do anything meaningful with it.
Returning means you want the script to continue. Continuing might mean having the caller raise SystemExit, or it might mean ignoring the error, or it might mean something else. Whatever it means is up to you, as you're the one writing the code.
Finally, are you sure you should be handling this error at all? Catching an exception only to turn it into a system shutdown may not be the most useful behavior. It's not a user-friendly way to deal with problems, and it hides all the useful debugging information you'd get from a stack trace.
You can raise an error with a 'returning_value' argument to be used after the calling.
Another pythonic answer to your problem could be to make use of the error arguments in the raise and then, in your call manage the error to get the value, convert it from string and get your 'return-ish'.
def your_f():
try:
some_io_thingy_ok()
return 1
except IOError:
raise SystemExit("FOOBAR", 0)
try:
my_returning_value = your_f()
except SystemExit as err:
my_returning_value = err.args[1]
print(my_returning_value)
From Python 3 docs :
When an exception occurs, it may have an associated value, also known
as the exception’s argument. The presence and type of the argument
depend on the exception type.
The except clause may specify a variable after the exception name. The
variable is bound to an exception instance with the arguments stored
in instance.args. For convenience, the exception instance defines
str() so the arguments can be printed directly without having to reference .args. One may also instantiate an exception first before
raising it and add any attributes to it as desired.
To exit a script and return an exit status, use sys.exit():
import sys
sys.exit(value_to_return)
I think what you may be looking for is something more like this:
def some_function():
# this function should probably do some stuff, then return 1 if
# it was successful or 0 otherwise.
pass
def calling_function():
a = some_function()
if a == 1:
raise SystemExit('Get the heck outta here!')
else:
# Everything worked!
pass
You can't "raise" and "return" in the same time, so you have to add a special variable to the return value (e.g: in tuple) in case of error.
E.g:
I have a function (named "func") which counts something and I need the (partial) result even if an exception happened during the counting. In my example I will use KeyboardInterrupt exception (the user pressed CTRL-C).
Without exception handling in the function (it's wrong, in case of any exception the function doesn't give back anything):
def func():
s=0
for i in range(10):
s=s+1
time.sleep(0.1)
return s
x=0
try:
for i in range(10):
s=func()
x=x+s
except KeyboardInterrupt:
print(x)
else:
print(x)
And now I introduce a boolean return value (in a tuple, next to the original return value) to indicate if an exception happened. Because in the function I handle only the KeyboardInterrupt exception, I can be sure that's happened, so I can raise the same where I called the function:
def func():
try:
s=0
for i in range(10):
s=s+1
time.sleep(0.1)
except KeyboardInterrupt: # <- the trick is here
return s, True # <- the trick is here
return s, False # <- the trick is here
x=0
try:
for i in range(10):
s,e=func()
x=x+s
if e: # <- and here
raise KeyboardInterrupt # <- and here
except KeyboardInterrupt:
print(x)
else:
print(x)
Note: my example is python3. The time module is used (in both code above), but I haven't import it just to make it shorter. If you want to really try it, put at the beginning:
import time
i was looking for an answer without using try, use 'finally' keyword like this.. if any one knows fill me in
here is an answer for your poblem
try:
9/0#sample error "don't know how to make IOError"
except ZeroDivisionError:
value_to_return = 0
raise SystemExit("FOOBAR")
finally:return value_to_return

What are exceptions in Python?

I've read three beginner-level Python books, however, I still don't understand exceptions.
Could someone give me a high level explanation?
I guess I understand that exceptions are errors in code or process that cause the code to stop working.
In the old days, when people wrote in assembly language or C, every time you called a function that might fail, you had to check whether it succeeded. So you'd have code like this:
def countlines(path):
f = open(path, 'r')
if not f:
print("Couldn't open", path)
return None
total = 0
for line in f:
value, success = int(line)
if not success:
print(line, "is not an integer")
f.close()
return None
total += value
f.close()
return total
The idea behind exceptions is that you don't worry about those exceptional cases, you just write this:
def countlines(path):
total = 0
with open(path, 'r') as f:
for line in f:
total += int(line)
return total
If Python can't open the file, or turn the line into an integer, it will raise an exception, which will automatically close the file, exit your function, and quit your whole program, printing out useful debugging information.
In some cases, you want to handle an exception instead of letting it quit your program. For example, maybe you want to print the error message and then ask the user for a different filename:
while True:
path = input("Give me a path")
try:
print(countlines(path))
break
except Exception as e:
print("That one didn't work:", e)
Once you know the basic idea that exceptions are trying to accomplish, the tutorial has a lot of useful information.
If you want more background, Wikipedia can help (although the article isn't very useful until you understand the basic idea).
If you still don't understand, ask a more specific question.
The best place to start with that is Python's list of built-in exceptions, since most you'll see derive from that.
Keep in mind that anybody can throw any error they want over anything, and then catch it and dismiss it as well. Here's one quick snippet that uses exceptions for handling instead of if/else where __get_site_file() throws an exception if the file isn't found in any of a list of paths. Despite that particular exception, the code will still work. However, the code would throw an uncaught error that stops execution if the file exists but the permissions don't allow reading.
def __setup_site_conf(self):
# Look for a site.conf in the site folder
try:
path = self.__get_site_file('site.conf')
self.__site_conf = open(path).read()
except EnvironmentError:
self.__site_conf = self.__get_site_conf_from_template()
Python's documentation: http://docs.python.org/2/tutorial/errors.html
For a high-level explanation, say we want to divide varA / varB. We know that varB can't equal 0, but we might not want to perform the check every time we do the division:
if varB != 0:
varA / varB
We can use exceptions to try the block without performing the conditional first, and then handle the behavior of the program based on whether or not something went wrong in the try block. In the following code, if varB == 0, then 'oops' is printed to the console:
try:
varA / varB
except ZeroDivisionError:
print 'oops'
Here is a list of exceptions that can be used: http://docs.python.org/2/library/exceptions.html#exceptions.BaseException
However, if you know how it may fail, you can just open a python console and see what exception is raised:
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Exceptions are unexpected events that occur during the execution of a program. An exception might result from a logical error or an unanticipated situation.
In Python, exceptions (also known as errors) are objects that are raised (or thrown) by code that encounters an unexpected circumstance.
The Python interpreter can also raise an exception should it encounter an unexpected condition, like running out of memory. A raised error may be caught by a surrounding context that “handles” the exception in an appropriate fashion.
If uncaught, an exception causes the interpreter to stop executing the program and to report an appropriate message to the console.
def sqrt(x):
if not isinstance(x, (int, float)):
raise TypeError( x must be numeric )
elif x < 0:
raise ValueError( x cannot be negative )
Exceptions are not necessarily errors. They are things that get raised when the code encounters something it doesn't (immediately) know how to deal with. This may be entirely acceptable, depending on how you make your code. For instance, let's say you ask a user to put in a number. You then try to take that text (string) and convert it to a number (int). If the user put in, let's say, "cat", however, this will raise an exception. You could have your code handle that exception, however, and rather than break, just give the user a small message asking him to try again, and please use a number. Look at this link to see what I'm talking about: http://www.tutorialspoint.com/python/python_exceptions.htm
Also, you usually handle exceptions with a try, except (or catch) block. Example:
try:
integer = int(raw_input("Please enter an integer: "))
except Exception, exc:
print "An error has occured."
print str(exc)
Hope it helps!

Categories

Resources