Ask your own question, for FREE!
Computer Science 22 Online
OpenStudy (blackstreet23):

What does try/except mean in python? What is their difference with if/elif/else? And, how do you use them (try/except)?

OpenStudy (turingtest):

`try/except` blocks are ways of handling errors in python so that you can control what happens in your program when an error is 'thrown' ("throwing" and error is the CS term for having an error come up)

OpenStudy (turingtest):

it's completely different from `if/elif/else` because if an error comes up within an `if/else` block your program will simply halt and you will get some built-in error message in red that tries to describe what went wrong.

OpenStudy (turingtest):

with `try/except` you can allow the code to keep running, or output a customized error message instead of just stopping alltogether

OpenStudy (turingtest):

do you know how to define functions yet? I can give an example if you do

OpenStudy (anonymous):

see if you tried to open a file in python which is either not there on disk or you don't have permission to open it, then generally the program will throw an error saying that the file can't be accessed.

OpenStudy (anonymous):

``` try: fh = open("testfile", "w") except IOError: print "Error: can\'t find file or read data" ``` IOError is the predefined error type for these types of error.

OpenStudy (anonymous):

with this try and except you can give meaningfull messages to the user about the error message.

OpenStudy (turingtest):

if you try running this code: ``` n = 5 while True: print float(5)/n n = n - 1 ``` you will print out 5/n until n becomes zero, at which point you will get some kind of error (I think it is a `ValueError`, which is a predefined error like `IOError` as Sandeep described). However if you change it to this: ``` n = 5 while True: try: print float(5)/n n = n - 1 except: print "Never divide by zero!" break ``` When the python tries to throw an error the code will instead jump to the `except` block, and no error will come up. (when you don't specify the kind of error in the `except` statement it responds to all errors the same way)

OpenStudy (anonymous):

http://prntscr.com/5rcjf5

OpenStudy (anonymous):

with that said, https://docs.python.org/2/tutorial/errors.html

OpenStudy (blackstreet23):

ohh ok. I get it now TuringTest. However, how could you specify the type of error, so except does not generalizes?

OpenStudy (anonymous):

?

OpenStudy (anonymous):

``` We can handle exceptions using the try..except statement. We basically put our usual statements within the try-block and put all our error handlers in the except-block. Example (save as exceptions_handle.py): try: text = raw_input('Enter something --> ') except EOFError: print 'Why did you do an EOF on me?' except KeyboardInterrupt: print 'You cancelled the operation.' else: print 'You entered {}'.format(text) Output: # Press ctrl + d $ python exceptions_handle.py Enter something --> Why did you do an EOF on me? # Press ctrl + c $ python exceptions_handle.py Enter something --> ^CYou cancelled the operation. $ python exceptions_handle.py Enter something --> No exceptions You entered No exceptions How It Works We put all the statements that might raise exceptions/errors inside the try block and then put handlers for the appropriate errors/exceptions in the except clause/block. The except clause can handle a single specified error or exception, or a parenthesized list of errors/exceptions. If no names of errors or exceptions are supplied, it will handle all errors and exceptions. Note that there has to be at least one except clause associated with every try clause. Otherwise, what’s the point of having a try block? If any error or exception is not handled, then the default Python handler is called which just stops the execution of the program and prints an error message. We have already seen this in action above. You can also have an else clause associated with a try..except block. The else clause is executed if no exception occurs. In the next example, we will also see how to get the exception object so that we can retrieve additional information. ```

OpenStudy (anonymous):

```python try: text = raw_input('Enter something --> ') except EOFError: print 'Why did you do an EOF on me?' except KeyboardInterrupt: print 'You cancelled the operation.' else: print 'You entered {}'.format(text) ``` save the above as exceptions_handle.py and try above.

OpenStudy (turingtest):

In the case of the example I gave you it was a `ZeroDivisionError`, so if you had put ``` n = 5 while True: try: print float(5)/n n = n - 1 except ZeroDivisionError: print "Never divide by zero!" break ``` it would only go to the print statement if the error is dividing by zero. If you put check for the wrong kind of error after in the `except` statement you will just get the pre-defined error message. For instance earlier I mistakenly guessed that dividing by zero gave a `ValueError` (it does not), so if you do ``` n = 5 while True: try: print float(5)/n n = n - 1 except ValueError: print "Never divide by zero!" break ``` You will still get a pre-defined error message because our `except` statement "catches the wrong error"

OpenStudy (turingtest):

In other words, in the second case above, `except` won't know when we divide by zero because it is looking for the wrong kind of error.

OpenStudy (blackstreet23):

try: text = raw_input('Enter something --> ') except EOFError: print 'Why did you do an EOF on me?' except KeyboardInterrupt: print 'You cancelled the operation.' else: print 'You entered {}'.format(text) What is an EOFError? What is a KeyboardInterrupt? In print 'You entered {}'.format(text) what are {} used for also ".format (text)"? Isnt format used right after the print function call?

OpenStudy (blackstreet23):

also what does raw_input means? isnt just said input?

OpenStudy (turingtest):

to see what `raw_input()` does, try a script like this ``` name = raw_input("what is your name?") print "Hello, " + name ```

OpenStudy (turingtest):

`EOF` means "end of file" and is common throughout all CS `EOFError` then means "end of file error" Keyboard interrupt is CTRL+C usually on windows, and stops the program manually. It's good for when your program gets stuck in an infinite loop or something and you want to force quite.

OpenStudy (turingtest):

as far as your question about formatting, there are many ways to make the same print statement in python: ``` name = raw_input("what is your name?") print "Hello, " + name print "Hello,", name print "Hello, %s" % (name) print "Hello, {0}".format(name) ```

OpenStudy (anonymous):

did I add those questions up your sleeve @blackstreet23 ? :) @TuringTest I think i made you to work on this little bit :P :D

OpenStudy (turingtest):

Lol no worries, one thing tends to lead to another like that :P

OpenStudy (blackstreet23):

Traceback (most recent call last): File "C:/Users/Romeo/OneDrive/Python winter vacation knowledge improvement/Raw_input/Raw_input.py", line 1, in <module> name = raw_input("what is your name?") NameError: name 'raw_input' is not defined

OpenStudy (blackstreet23):

It says raw input it not defined :(

OpenStudy (blackstreet23):

are you sure that raw_input is a valid form of inputting?

OpenStudy (turingtest):

Yes, I am very sure. http://prntscr.com/5rk3da Did you open a new window with CTRL+N, then paste the code into that new window, then hit F5 to run it?

OpenStudy (anonymous):

@blackstreet and @TuringTest in python 3.x, raw_input is deprecated . input() is used instead of raw_input() in python 3.x versions.

OpenStudy (turingtest):

Ah, I see, thanks. I don't use 3.x. I only tried it out once and it annoyed me.

OpenStudy (anonymous):

@TuringTest , Guido van Rossum -inventor of python - got serious on it and made some fundamental changes to 2.x which are not backwards compatible with 2.x like this raw_input deprecation and "making "print" a function which was a statement in 2.x Extra Info: Many projects in production are still using the 2.x python nonetheless :) :D Some tools are there which can convert py3.x scripts to py2.x and vice-versa :)

OpenStudy (turingtest):

I have yet to see a course based on anything other than python 2.7.x, so I didn't take learning 3.x seriously. I didn't know van Rossum was so personally involved in the new release, nor did I know about the script conversion tools; I'll be looking into those. Thanks!

OpenStudy (anonymous):

:) :)

OpenStudy (blackstreet23):

Thank you a lot for your answers!!!!

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!