Monday, October 9, 2023

Exception Handling in Python (Theory)

Try, Except

This statement controls how the program proceeds when an error occurs. The syntax is as follows:

try:
	do something
except:
	do something else when an error occurs

For instance, try running the program below:- 

try:
	answer = 12/0
	print(answer) 
except:
	print ("An error occurred")

Exception We Saw: ZeroDivisionError

Exception We Saw: ValueError

Exception We Saw: IndexError

Getting a default value on index out of range in Python

In the non-Python spirit of "ask for permission, not forgiveness", here's another way: b = a[4] if len(a) > 4 else '-1'

Exception We Saw: NameError

We see this error while working with “del” keyword.

Exception We Saw: KeyError

Use case: We see this exception while working with remove() and discard() methods of a set.

Another example of KeyError While Working With Dict And How to Avoid It

Exception We Saw: TypeError

Other common errors in Python

IOError:

Raised when an I/O operation (such as the built-in open() function) fails for an I/O-related reason, e.g., “file not found”.

ImportError: Raised when an import statement fails to find the module definition

IndexError: Raised when a sequence (e.g. string, list, tuple) index is out of range.

KeyError: Raised when a dictionary key is not found.

NameError: Raised when a local or global name is not found.

TypeError: Raised when an operation or function is applied to an object of inappropriate type.

No comments:

Post a Comment