# Exception Handling

### Exception Handling :

Like other languages, python also provides the runtime errors via exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError.

Example 1:

```python
# Python program to handle simple runtime error 

a = [1, 2, 3] 
try: 
    print("Second element = %d"%(a[1]))

    # Throws error since there are only 3 elements in array 
    print("Fourth element = %d"%(a[3]) )

except IndexError: 
    print("An error occurred")

```

Second element = 2&#x20;

An error occurred

Example 2:

```python
# Program to handle multiple errors with one except statement 
try : 
	a = 3
	if a < 4 : 

		# throws ZeroDivisionError for a = 3 
		b = a/(a-3) 
	
	# throws NameError if a >= 4 
	print("Value of b = ", b)

# note that braces () are necessary here for multiple exceptions 
except(ZeroDivisionError, NameError): 
	print("\nError Occurred and Handled")

```

Error Occurred and Handled

Else Clause

Example 3:

```python
# Program to depict else clause with try-except 

# Function which returns a/b 
def AbyB(a , b): 
	try: 
		c = ((a+b) / (a-b)) 
	except ZeroDivisionError: 
		print("a/b result in 0")
	else: 
		print(c)
	finally:
		print("success")

# Driver program to test above function 
AbyB(2.0, 3.0) 
AbyB(3.0, 3.0) 

```

-5.0&#x20;

a/b result in 0

success

Example 4:

```python
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!",sys.exc_info()[0],"occured.")
        print("Next entry.")
        print()
print("The reciprocal of",entry,"is",r)
```

&#x20;The entry is a&#x20;

Oops! \<class 'ValueError'>  occured.&#x20;

Next entry.

The entry is 0&#x20;

Oops! \<class 'ValueError'> occured.&#x20;

Next entry.

The entry is 2&#x20;

The reciprocal of 2 is 0.5


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-python.gitbook.io/python-programming/oops/exception-handling.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
