Python Exception Handling

5,261 views 20 slides Jan 25, 2022
Slide 1
Slide 1 of 20
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20

About This Presentation

Python Exception Handling


Slide Content

Unit 3 Python Exception handling 25-01-2022 [email protected] 1

Python Errors and Exceptions Encountering  errors and exceptions  can be very frustrating at times, and can make coding feel like a hopeless endeavor. However, understanding what the  different types of errors  are and when you are likely to encounter them can help a lot. Python Errors can be of three types: Compile time errors (Syntax errors) Runtime errors (Exceptions) Logical errors 25-01-2022 [email protected] 2

Compile time errors (Syntax errors) Errors caused by not following the  proper structure (syntax)  of the language are called syntax or parsing errors. Runtime errors (Exceptions) Exceptions occur during run-time. Your code may be syntactically correct but it may happen that during run-time Python encounters something  which it can't handle  , then it raises an exception. 25-01-2022 [email protected] 3

Logical errors Logical errors are the most difficult to fix. They occur when the program runs without crashing, but produces an incorrect result. The error is caused by a mistake in the  program's logic  . You won't get an error message, because no syntax or runtime error has occurred. 25-01-2022 [email protected] 4

Python Exception Handling The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks. When an error occurs, or exception as we call it, Python will normally stop and generate an error message. 25-01-2022 [email protected] 5

Python Exception Handling These exceptions can be handled using the try statement: Example The try block will generate an exception, because x is not defined: try :    print (x) except :    print ( "An exception occurred" ) 25-01-2022 [email protected] 6

Since the try block raises an error, the except block will be executed. Without the try block, the program will crash and raise an error: Example This statement will raise an error, because x is not defined: print (x) 25-01-2022 [email protected] 7

Example: try: a=int(input(“First Number:”)) b=int(input(“Second number”)) result=a/b print(“Result=”,result) except ZeroDivisionError : print(“Division by zero”) else: print(“Successful division”) Output First Number:10 Second number:0 Division by zero 25-01-2022 [email protected] 8

Except clause with multiple exceptions try: a=int(input(“First Number:”)) b=int(input(“Second Number:”)) result=a/b print(“Result=”,result) except( ZeroDivisionError , TypeError ): print(“Error occurred”) else: print(“Successful Division”) Output First Number:10 Second Number:0 Error occured 25-01-2022 [email protected] 9

try......finally A finally block can be used with a try block The code placed in the finally block is executed no matter Exception is caused or caught We cannot use except clause and finally clause together with a try block It is also not possible to use else clause and finally together with try block. Syntax: try: suite; finally: finally_suite # Executed always after the try block 25-01-2022 [email protected] 10

Example: try: a=int(input(“First Number:”)) b=int(input(“Second number”)) result=a/b print(“Result=”,result) finally: print(“Executed always”) Output First Number:20 Second number:0 Executed always Traceback (most recent call last): File “main.py”, line 5, in <module> result=a/b ZeroDivisionError : integer division or modulo by zero 25-01-2022 [email protected] 11

Some of the common in-built exceptions are as follows: ZeroDivisionError - Raised when division or modulo by zero takes place for all numeric types. NameError - Raised when name of keywords, identifiers.. etc are wrong IndentationError - Raised when indentation is not properly given IOError - Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. EOFError - Raised when there is no input from either the raw_input () or input() function and the end of file is reached. 25-01-2022 [email protected] 12

Python - Assert Statement In Python, the assert statement is used to continue the execute if the given condition evaluates to True. If the assert condition evaluates to False, then it raises the AssertionError exception with the specified error message. Syntax assert condition [, Error Message] The following example demonstrates a simple assert statement. Example: x = 10 assert x > 0 print('x is a positive number.') Output x is a positive number. In the above example, the assert condition, x > 0 evaluates to be True, so it will continue to execute the next statement without any error. 25-01-2022 [email protected] 13

The assert statement can optionally include an error message string, which gets displayed along with the AssertionError . Consider the following assert statement with the error message. Example: Assert Statement with Error Message x = 0 assert x > 0, 'Only positive numbers are allowed’ print('x is a positive number.') Output Traceback (most recent call last): assert x > 0, 'Only positive numbers are allowed' AssertionError : Only positive numbers are allowed 25-01-2022 [email protected] 14

Python Program for User-defined Exception Handling: class YourException (Exception): def __ init __(self, message): self.message = message try: raise YourException ("Something is wrong") except YourException as err: # perform any action on YourException instance print("Message:", err.message ) 25-01-2022 [email protected] 15

User-defined Exception Handling: Example class Error(Exception): pass class ValueTooSmallError (Error): pass class ValueTooLargeError (Error): pass 25-01-2022 [email protected] 16

Cont.. #Main Program number=10 while True: try: i_num =int(input(“Enter a number:”)) if i_num <number: raise ValueTooSmallError elif i_num >number: raise ValueTooLargeError break except ValueTooSmallError : print(“This value is too small ! Please try again”) except ValueTooLargeError : print(“This value is too large! Please try again”) print(“Congratulations…You guesses it correctly”) 25-01-2022 [email protected] 17

Logging the exceptions Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. To log an exception in Python we can use  logging  module and through that we can log the error. Logging module provides a set of functions for simple logging and for following purposes DEBUG INFO WARNING ERROR CRITICAL 25-01-2022 [email protected] 18

Logging the exceptions Logging an exception in python with an error can be done in the  logging.exception ()  method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler. 25-01-2022 [email protected] 19

Example: 25-01-2022 [email protected] 20 # importing the module import logging   try :      printf ( “Good Morning" ) except Exception as Argument:      logging.exception ( "Error occurred while printing Good Morning" )