Exception Handling 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

Python Exceptions Handling

• Error in Python can be of two types i.e.


Syntax errors and Exceptions. Errors are the problems in a
program due to which the program will stop the execution. On the
other hand, exceptions are raised when some internal events
occur which changes the normal flow of the program.

Python provides two very important features to handle any


unexpected error in your Python programs and to add debugging
capabilities in them:
– Exception Handling: This would be covered in this tutorial.
– Assertions: This would be covered in Assertions in Python
tutorial.
What is Exception?
• An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's
instructions.
• In general, when a Python script encounters a situation that it
can't cope with, it raises an exception. An exception is a Python
object that represents an error.
• When a Python script raises an exception, it must either handle
the exception immediately otherwise it would terminate and
come out.
Handling an exception:
• If you have some suspicious code that may raise an exception,
you can defend your program by placing the suspicious code in a
try: block. After the try: block, include an except: statement,
followed by a block of code which handles the problem as
elegantly as possible.
Syntax:
try:
You do your operations here;
......................
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points above the above mentioned syntax:
• A single try statement can have multiple except statements. This
is useful when the try block contains statements that may throw
different types of exceptions.
• You can also provide a generic except clause, which handles any
exception.
• After the except clause(s), you can include an else-clause. The
code in the else-block executes if the code in the try: block does
not raise an exception.
• The else-block is a good place for code that does not need the try:
block's protection.
• Difference between Syntax Error and Exceptions
• Syntax Error: As the name suggests this error is caused by the
wrong syntax in the code. It leads to the termination of the
program.
Example:
# initialize the amount variable
amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Exceptions

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)
The except clause with no exceptions:
You can also use the except statement with no exceptions
defined as follows:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this
block. ......................
else:
If there is no exception then execute this block.

This kind of a try-except statement catches all the


exceptions that occur. Using this kind of try-except
statement is not considered a good programming practice,
though, because it catches all exceptions but does not make
the programmer identify the root cause of the problem that
may occur.
The except clause with multiple exceptions:
You can also use the same except statement to handle multiple
exceptions as follows:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception
list, then execute this block
.......................
else:
If there is no exception then execute this block.
Standard Exceptions:
Here is a list standard Exceptions available in Python:
Standard Exceptions
The try-finally clause:
You can use a finally: block along with a try: block. The finally
block is a place to put any code that must execute, whether the
try-block raised an exception or not. The syntax of the try-finally
statement is this:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but
not both. You can not use else clause as well along with a finally
clause.
Example:
# Python program to handle simple runtime error
#Python 3
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in
array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")

In the above example, the statements that can cause the error are placed
inside the try statement (second print statement in our case). The second
print statement tries to access the fourth element of the list which is not
there and this throws an exception. This exception is then caught by the
except statement.
Catching Specific Exception
• A try statement can have more than one except clause, to specify
handlers for different exceptions. Please note that at most one
handler will be executed. For example, we can add IndexError in
the above code. The general syntax for adding specific exceptions
are –

try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exception in Python
# Program to handle multiple errors with one
# except statement
# Python 3
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
• Try with Else Clause
• In python, you can also use the else clause on the try-except
block which must be present after all the except clauses. The
code enters the else block only if the try clause does not raise an
exception.
• Example: Try with else clause
# Program to depict else clause with try-except
# Python 3
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
• Finally Keyword in Python
• Python provides a keyword finally, which is always executed after
the try and except blocks. The final block always executes after
normal termination of try block or after try block terminates due
to some exception.
• Syntax:
• try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
# Python program to demonstrate finally

# No exception Exception raised in try block


try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Raising Exception
The raise statement allows the programmer to force a specific
exception to occur. The sole argument in raise indicates the
exception to be raised. This must be either an exception instance
or an exception class (a class that derives from Exception).

# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or
not
The output of the above code will simply line printed as “An
exception” but a Runtime error will also occur in the last due
to the raise statement in the last line. So, the output on your
command line will look like

Traceback (most recent call last):


File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5,
in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
Python Try Except
Error in Python can be of two types i.e. Syntax errors and
Exceptions. Errors are the problems in a program due to which the
program will stop the execution. On the other hand, exceptions are
raised when some internal events occur which changes the normal
flow of the program.

Some of the common Exception Errors are :

IOError: if the file can’t be opened


KeyboardInterrupt: when an unrequired key is pressed by the user
ValueError: when built-in function receives a wrong argument
EOFError: if End-Of-File is hit without reading any data
ImportError: if it is unable to find the module
Try Except in Python
Try and Except statement is used to handle these errors within our
code in Python. The try block is used to check some code for errors
i.e the code inside the try block will execute when there is no error
in the program. Whereas the code inside the except block will
execute whenever the program encounters some error in the
preceding try block.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block
How try() works?

First, the try clause is executed i.e. the code between try and
except clause.
If there is no exception, then only the try clause will run, except
the clause is finished.
If any exception occurs, the try clause will be skipped and except
clause will run.
If any exception occurs, but the except clause within the code
doesn’t handle it, it is passed on to the outer try statements. If the
exception is left unhandled, then the execution stops.
A try statement can have more than one except clause
Code 1: No exception, so the try clause will run.
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as
Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program


divide(3, 2)
Else Clause

In python, you can also use the else clause on the try-except
block which must be present after all the except clauses. The
code enters the else block only if the try clause does not raise an
exception.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
# Program to depict else clause with try-except

# Function which returns a/b


def AbyB(a , b):
try:
c = ((a+b) // (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Finally Keyword in Python
Python provides a keyword finally, which is always executed after
the try and except blocks. The final block always executes after
normal termination of try block or after try block terminates due
to some exceptions.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
# Python program to demonstrate finally

# No exception Exception raised in try block


try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Some of the common built-in exceptions are other
than above mention exceptions are:

Exception Description

IndexError When the wrong index of a list is retrieved.

AssertionError It occurs when the assert statement fails

AttributeError It occurs when an attribute assignment is failed.

ImportError It occurs when an imported module is not found.

It occurs when the key of the dictionary is not


KeyError
found.

NameError It occurs when the variable is not defined.

MemoryError It occurs when a program runs out of memory.

It occurs when a function and operation are


TypeError
applied in an incorrect type.
• User-defined Exceptions in Python with Examples
• Programmers may name their own exceptions by creating a
new exception class. Exceptions need to be derived from
the Exception class, either directly or indirectly. Although
not mandatory, most of the exceptions are named as
names that end in “Error” similar to the naming of the
standard exceptions in python. For example:
# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):

# Constructor or Initializer
def __init__(self, value):
self.value = value

# __str__ is to print() the value


def __str__(self):
return(repr(self.value))

try:
raise(MyError(3*2))

# Value of Exception is stored in error


except MyError as error:
print('A New Exception occurred: ', error.value)
Python Tkinter
Tkinter is the most commonly used library for developing GUI
(Graphical User Interface) in Python. It is a standard Python
interface to the Tk GUI toolkit shipped with Python. As Tk and
Tkinter are available on most of the Unix platforms as well as on
the Windows system, developing GUI applications with Tkinter
becomes the fastest and easiest.

Graphical User Interface(GUI) is a form of user interface


which allows users to interact with computers through visual
indicators using items such as icons, menus, windows, etc. It has
advantages over the Command Line Interface(CLI) where users
interact with computers by writing commands using keyboard
only and whose usage is more difficult than GUI.
What is tkinter

Tkinter is the inbuilt python module that is used to create GUI


applications. It is one of the most commonly used modules for
creating GUI applications in Python as it is simple and easy to
work with. You don’t need to worry about the installation of the
Tkinter module separately as it comes with Python already. It
gives an object-oriented interface to the Tk GUI toolkit.

Some other Python Libraries available for creating our own GUI
applications are

Kivy
Python Qt
wxPython
What are Widgets
Widgets in Tkinter are the elements of GUI application which
provides various controls (such as Labels, Buttons,
ComboBoxes, CheckBoxes, MenuBars, RadioButtons and many
more) to users to interact with the application.

Fundamental structure of tkinter program


Basic Tkinter Widgets:
Widgets Description
Label It is used to display text or image on the screen
Button It is used to add buttons to your application

Canvas It is used to draw pictures and others layouts like texts, graphics etc.

ComboBox It contains a down arrow to select from list of available options


It displays a number of options to the user as toggle buttons from which user can
CheckButton
select any number of options.
It is used to implement one-of-many selection as it allows only one option to be
RadiButton
selected
Entry It is used to input single line text entry from user
Frame It is used as container to hold and organize the widgets

Message It works same as that of label and refers to multi-line and non-editable text

It is used to provide a graphical slider which allows to select any value from that
Scale
scale

Scrollbar It is used to scroll down the contents. It provides a slide controller.

SpinBox It is allows user to select from given set of values

Text It allows user to edit multiline text and format the way it has to be displayed

Menu It is used to create all kinds of menu used by an application


Example
from tkinter import *
from tkinter.ttk import *

# writing code needs to


# create the main window of
# the application creating
# main window object named root
root = Tk()

# giving title to the main window


root.title("First_Program")

# Label is what output will be


# show on the window
label = Label(root, text ="Hello World !").pack()

# calling mainloop method which is used


# when your application is ready to run
# and it tells the code to keep displaying
root.mainloop()
Creating Button
from tkinter import *
# create root window
root = Tk()
# frame inside root window
frame = Frame(root)
# geometry method
frame.pack()
# button inside frame which is
# inside root
button = Button(frame, text ='Geek')
button.pack()
# Tkinter event loop
root.mainloop()
Geometry Management
Creating a new widget doesn’t mean that it will appear on the screen.
To display it, we need to call a special method:
either grid, pack(example above), or place.

Method Description

pack() The Pack geometry manager packs widgets in rows or columns.

The Grid geometry manager puts the widgets in a 2-dimensional


table.
grid()
The master widget is split into a number of rows and columns, and
each “cell” in the resulting table can hold a widget.

The Place geometry manager is the simplest of the three general


geometry managers provided in Tkinter.
place()
It allows you explicitly set the position and size of a window, either in
absolute terms, or relative to another window.
# import everything from tkinter module
from tkinter import *

# create a tkinter window


root = Tk()
# Open window having dimension 100x100
root.geometry('100x100')
# Create a Button
btn = Button(root, text = 'Click me !', bd = '5',
command =
root.destroy)
# Set the position of button on the top of window.
btn.pack(side = 'top')
root.mainloop()

You might also like