Nearby lessons

71 of 108

Python - Exception Handling

Detailed Tutorial Notes

Exception Handling

In any programming language there are 2 types of errors are possible.

  • Syntax Errors
  • Runtime Errors
  • Syntax Errors: The errors which occurs because of invalid syntax are called syntax errors. Eg 1: x=10 if x==10
print("Hello")
SyntaxError: invalid syntax

Eg 2:

print "Hello"

SyntaxError: Missing parentheses in call to 'print'

Note:

Programmer is responsible to correct these syntax errors. Once all syntax errors are

corrected then only program execution will be started.

  • Runtime Errors: Also known as exceptions. While executing the program if something goes wrong because of end user input or programming logic or memory problems etc then we will get Runtime Errors.
Eg: print(10/0) ==>ZeroDivisionError: division by zero
print(10/"ten") ==>TypeError: unsupported operand type(s) for /: 'int' and 'str'

x=int(input("Enter Number:"))

print(x)

D:\Python_classes>py test.py

Enter Number:ten

ValueError: invalid literal for int() with base 10: 'ten'

Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors

What is Exception:

An unwanted and unexpected event that disturbs normal flow of program is called

exception.

Eg:

ZeroDivisionError

TypeError

ValueError

FileNotFoundError

EOFError

SleepingError

TyrePuncturedError

It is highly recommended to handle exceptions. The main objective of exception handling

is Graceful Termination of the program(i.e we should not block our resources and we

should not miss anything)

Exception handling does not mean repairing exception. We have to define alternative way

to continue rest of the program normally.

Eg:

For example our programming requirement is reading data from remote file locating at

London. At runtime if london file is not available then the program should not be

terminated abnormally. We have to provide local file to continue rest of the program

normally. This way of defining alternative is nothing but exception handling.

try:

read data from remote file locating at london

except FileNotFoundError:

use local file and continue rest of the program normally

Q. What is an Exception?

Q. What is the purpose of Exception Handling?

Q. What is the meaning of Exception Handling?

Default Exception Handing in Python:

Every exception in Python is an object. For every exception type the corresponding classes

are available.

Whevever an exception occurs PVM will create the corresponding exception object and

will check for handling code. If handling code is not available then Python interpreter

terminates the program abnormally and prints corresponding exception information to

the console.

The rest of the program won't be executed.

Eg:

1) print("Hello")
2) print(10/0)
3) print("Hi")

4)

5) D:\Python_classes>py test.py
6) Hello
7) Traceback (most recent call last):
8) File "test.py", line 2, in <module>
9) print(10/0)
10) ZeroDivisionError: division by zero

Python's Exception Hierarchy

Every Exception in Python is a class.

All exception classes are child classes of BaseException.i.e every exception class extends

BaseException either directly or indirectly. Hence BaseException acts as root for Python

Exception Hierarchy.

Most of the times being a programmer we have to concentrate Exception and its child

classes.

Customized Exception Handling by using try-except:

It is highly recommended to handle exceptions.

The code which may raise exception is called risky code and we have to take risky code

inside try block. The corresponding handling code we have to take inside except block.

Attribute

Error

Arithmetic

Error

EOF

Error

Name

Error

Lookup

Error

OS

Error

Type

Error

Value

Error

BaseException

Exception KeyboardInterrupt SystemExit GeneratorExit

ZeroDivision

Error

FloatingPoint

Error

Overflow

Error

Index

Error

Key

Error

FileNotFound

Error

Interrupted

Error

Permission

Error

TimeOut

Error

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Python - Try Except