Exceptions
Here is a simple code that requires a user to type in a number:
while True: age = int(input("Type in your guess : At what age Alexander the great died? : " )) print(age)
The code expects an integer input from the user.
Syntax errors are parsing errors that we've had lots of times while we're coding. For example, suppose we missed the colon(':') from the code above, we get the following complain:
File "e.py", line 1 while True ^ SyntaxError: invalid syntax
Note that the code was not executed at all. We got the syntax error while PYthon interpreter was doing parsing.
What if a user type in "dumb" instead of a number string?
Type in your guess : At what age Alexander the great died? : dumb Traceback (most recent call last): File "e.py", line 2, in <module> age = int(input("Type in your guess : At what age Alexander the great died? : " )) ValueError: invalid literal for int() with base 10: 'dumb'
The "ValueError" is one of the exceptions.
Even if a statement or expression is syntactically correct, it may cause an error when we execute it. Errors detected during execution are called exceptions and we want to handle (capture) them in our code.
Here are examples of exceptions:
>>> 1/0 Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero >>> a + 10 Traceback (most recent call last): File " ", line 1, in NameError: name 'a' is not defined >>> '10' + 10 Traceback (most recent call last): File " ", line 1, in TypeError: Can't convert 'int' object to str implicitly >>>
How can we use exceptions?
- Error Handling:
Python raises exceptions at runtime. We can catch (or ignore) and respond to the errors in our code. If we opt to ignore the raised exception, Python's default exception-handling kicks in and stops our code with an error message. So, if we don't like the default way of handling exception, we may want to catch it using "try". - Closing time operation:
We can use "try/finally" to guarantee the execution of a certain operation regardless of the presence or absence of exceptions in our code.
Let's put "try" and "finally" into the code:
# e.py while True: try: age = int(input("Type in your guess : Age of the Universe : " )) print(age) break except ValueError: print("Please make sure you type in an integer") except: break finally: print("age loop" )
Run it:
$ python e.py Type in your guess : Age of the Universe : dumb Please make sure you type in an integer age loop Type in your guess : Age of the Universe : 45,500 Please make sure you type in an integer age loop Type in your guess : Age of the Universe : 10 10 age loop
Note the line "except:" catches all other exceptions not caught in "except ValueError:".
Usually, Python raises exceptions for us but our code can raise exceptions as well:
>>> try: ... raise IndexError ... except IndexError: ... print('got exception raised by our code') ... got exception raised by our code
So far, the exceptions have been raised for the built-in exceptions.
We can define our own exceptions as shown below:
# e2.py class Negative(Exception): pass def oops(): raise Negative() try: age = int(input("Type in your guess : Age of the Universe : " )) print(age) if age <= 0: print('calling ooops') oops() except ValueError: print("Please make sure you type in an integer") except Negative: print("Please make sure you type in a positive integer") except: print("Somethings wrong!") finally: print("finally!" )
Run the code:
$ python e2.py Type in your guess : Age of the Universe : -10 -10 calling ooops Please make sure you type in a positive integer finally!
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization