Concise Python Tutorials

Source: Internet
Author: User
Tags exit stdin

When there is something abnormal in your program, the exception occurs. For example, when you want to read a file, the file does not exist. Or when the program is running, you accidentally delete it. These situations can be handled using exceptions.

What happens if you have some invalid statements in your program? Python raises and tells you that there is an error, so that you can handle the situation.

Error

Consider a simple print statement. If we mistakenly spell print as print, note that uppercase, so Python throws a syntax error.

>>> Print 'Hello World'
File "<stdin>", line 1
Print 'Hello World'
^
SyntaxError: invalid syntax
>>> print 'Hello World'
Hello World

We can observe that a syntaxerror is raised and the detected error location is printed. This is the wrong processor for this error to do the work.

Try.. Except

We tried to read a segment of the user's input. Press ctrl-d and see what happens.

>>> s = raw_input('Enter something --> ')
Enter something --> Traceback (most recent call last):
File "<stdin>", line 1, in ?
EOFError

Python raises an error called eoferror, which basically means that it finds an unexpected end of the file (represented by ctrl-d)

Next, we will learn how to handle such errors.

Handling Exceptions

We can use try. Except statements to handle exceptions. We put the usual statements in the try-block and put our error-handling statements in the except-block.

Example 13.1 Handling Exceptions

#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'

(source file: code/try_except.py)

Output

$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional!
Done

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.