0% found this document useful (0 votes)
19 views

CMPE-30032-Module-3-Exception-Handling-in-Python-1

Uploaded by

Sess Rin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

CMPE-30032-Module-3-Exception-Handling-in-Python-1

Uploaded by

Sess Rin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

CMPE 30032

Module 3
Exception Handling
TABLE OF
CONTENTS
01 What are Exceptions?
02 Example of
Exceptions Cases
03 Types of Exceptions
04 Handling an Unchecked
Exceptions
05 Examples
What is an Exception?
An exception is an error that happens during execution of a
program. When that error occurs, Python generate an exception
that can be handled, which avoids your program to crash.

Why use Exceptions?


Exceptions are convenient in many ways for handling errors and
special conditions in a program. When you think that you have a
code which can produce an error then you can use exception
handling.

Raising an Exception
IOError
Example - If the file
for Exception cannot be opened.
Cases:

ImportError - If python cannot find the


module

ValueError - Raised when a function


receives an argument that has
the right type but an inappropriate
value
Types of Exceptions
- Checked (Compile-time)
- Checked exceptions are checked at compile-time.
- Exceptions are “checked” because they are subject to the
“catch” or “specify requirement”
otherwise, the program code will not compile.
Examples: Invalid Syntax, Incorrect statements

- Unchecked (Runtime)
- Unchecked exceptions are not checked at compile time.
- Errors are not subject to the “catch” or “specify
requirement”.
Python Unchecked
Exceptions
SyntaxErro
a=1 ZeroDivision NameEr
rif a < 0 Error
num = 30
result = num/0
ror
print(resu
print("Negati print(result) lt)
ve")

TypeErro
num = “five”
ValueError Sample input:
num = int(input("Enter a
rresult = number: "))
two
num+5
result = num+2
print(result)
print(result)
Handling Unchecked
Exception

 try is used to test a block of code


for errors
 except is used to handle errors
 finally is used to execute block of
code regardless of
the result of the try and except
blocks
Exception Handling -
Structure
try:
# Try block of Statements
except <<Exception Class>>:
# Exception handling statements
finally:
# Finally block of statements
Using try…except
try:
print(age)
print(age) except:
print(“Age variable is not
defined")
Output: print(“You must assign a value
Traceback (most recent call last): first or
File "F:\DICTPython\Exception.py", line 1, in
<module> Output: declare it")
print(age)
NameError: name 'age' is not defined
Age variable is not defined
You must assign a value first
or declare it
Print a specific error message if the
try block raises a NameError
try:
print(age)
except NameError: This statement will be
print("Variable age is executed since the try
not defined") block encountered a
except: NameError
print("Something else
went wrong")

Output:
Variable age is not
defined
Else
else is used to define a block of code to be
executed
try: if no errors were raised
print("Hello
World")
except:
print("An error
occured") This statement will be
else: executed since there’s
print("No error") no error inside the try
block
Output:
Hello World
No error
Finally
finally block will be executed regardless if the
try block raises an errortry:
or not.
try:
print("Hello World") print(age)
except: except:
print("An error print("An error
occurred") occurred")
else: else:
print("No error") print("No error")
finally:
finally:
print(“Finished")
print(“Finished")
Output:
Hello World
Output:
An error occurred
No error
Finished
Finished
Raise an Exception
raise is used to throw an exception if a
condition
ageoccurs.
= -1
if age < 0:
raise Exception("Sorry, age is out of
range")

age = "30"
if not type(age) is int:
raise TypeError("Can accept integer
value only")
Exception Handling – Example
01
x = 10
y = 5
try:
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
finally:
print(“End of Program")
Exception Handling –
Example 02
x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")
Exception Handling –
Example 03
x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")
Exception Handling –
try:Example 04
x = int(input(“Enter the value of X : ”))
y = int(input(“Enter the value of Y : ”))
result = x / y
print(“ Answer : ", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
except ValueError:
print("Sorry ! You are dividing by zero ")
finally:
print(“End of Program")
Exception Handling – Example 05

try:
f = open("demo.txt")
f.write(“Python Programming")
except:
print("Something went wrong when writing to the file ")

finally:
f.close()
Exception Handling –
Example
try:
06
a = 3
if a < 4 :
b = a / (a-3)
print( “Value of b = “, b)
except(ZeroDivisionError, NameError):
print( “Error Occurred and Handled” )
except:
print ( “Unknown Exception” )
Exception Handling –
Example 07
try:
x = int(input("Enter the value of X : "))
y = int(input("Enter the value of Y : "))
print("Answer :", x / y)
except ZeroDivisionError:
print("Division by Zero Error")
else:
print("Else Block")
finally:
print("End of Program")
Programming Exercise:
Create a Simple App Calculator
1. The application will ask the user to choose one of the
four math operations (Addition, Subtraction, Multiplication
and Division)
2. The application will ask the user for two numbers
3. Display the result
4. The application will ask if the user wants to try again or
not.
5. If yes, repeat Step 1.
6. If no, Display “Thank you!” and the program will exit
7. Use Python Function and appropriate Exceptions to capture
errors during
runtime.

You might also like