Basics of exception handling

Basics of exception handling

Lesson Details:
June 29, 2020

I: Introduction

Python is a high level programming language. It’s used in many applications like website development, scientific computing, data analysis, artificial intelligence etc.

It’s ranked as one of the top programming languages to learn for beginners.

II: Body

A: Basics of exception handling

Exceptions are events that occur at runtime, which are not anticipated by the programmer. We handle these exceptions using try, except and else statements.

Try-except-else statements are mostly used with functions. A function may have an exception raised by it. The user of that function should not be aware of these exceptions being raised. Instead, user should use try-except statement to handle it.

An example is given below:

def func(): print('Starting Function') try: print('Executing Function') except NameError: print('Exception Raised') return 10 raise NameError except KeyError: print('Exception Raised') return 20 raise KeyError if __name__ == '__main__': print('Executing Main Code') x = func() print('Return Value : ', x) Output : Executing Main Code Returning 10 starting Function Executing Function Starting Function Exception Raised Starting Function Exception Raised Returning 20 Returning 10

B: Basics of Decorators

Decorators are commonly used to modify or annotate functions or methods. They are very useful in Python 3.6 because they allow us to modify functions without adding keywords like @property, @staticmethod etc.

They are only allowed on functions and not on classes. They are also called as wrappers because they wrap around original functions or methods. An example is shown below:

@decorator def print_me(message): print('Printing Message', message) print_me(42) print_me(42) Output : Printing Message 42 Printing Message 42

C: Basics of Functions and Modules

Functions help us to organize the code into smaller blocks that can be reused easily. Functions can receive input parameters and can return output values. Modules are used to store related functions and objects altogether. Also, modules provide a way to organize our code in order to avoid naming conflicts between two different libraries. The module name is global so we don’t need to import it explicitly to use any contents inside it. An example is shown below:

def add_two_numbers(a, b): print('Input value a : {}'.format(a)) print('Input value b : {}'.format(b)) return a + b add_two_numbers(1, 2) add_two_numbers(2, 3) add_two_numbers(3, 4) add_two_numbers(4, 5) add_two_numbers(5, 6) add_two_numbers(6, 7) Output : Input value a : 1 Input value b : 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

III: Conclusion

Course content