Example HTML page

Introduction to Exception Handling

Being a programmer everybody encounters errors. These can be very frustrating and make coding feel like a hopeless one. However understanding the errors and exceptions in a program it becomes easier to fix them.

Error and Exception

An Error “indicates serious problems that a reasonable application should not try to catch.” An Exception “indicates conditions that a reasonable application might want to catch.” Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Exception

An exception can be defined by the following ways:

  • An exception is an object in Python. It provides us information regarding an error which is found when you execute a program.
  • An exception is also said as an event that occurs during program execution and interrupts the flow of execution.

When a python program raises an exception, it must be handled immediately.

Why use Exceptions?

Exceptions are convenient in many ways of handling errors and special conditions in a program. If you have a code which can produce an error then you can use exception handling.

Differences between Error and Exception:

  Errors Exception
Indicates It indicates serious problems that are reasonable application should not try to catch. It indicates conditions that a reasonable application might want to catch.
Nature They are often fatal in nature and recovery. They are not fatal in all the cases.
Recovery They cannot be recovered once occurred. They are generally those problems from which a program can recover.
Handled or Not Handled Error is not meant to be caught. Exception meant to be caught.
Caused by These indicate a system error or a problem with a low-level resource. These are caused by a programmer.
Co-relation Errors are also unchecked exception. Exceptions are also Run-time errors.
Should be handled at the levels. Errors should be handled at the system level, if possible. Exceptions should be handled at application level.
Example Syntax Error IOException

Exception handling

The process of handling exceptions (that interrupts the normal execution flow of a program) during program execution like number divided by zero, accessing array out of bound and so on is known as “Exception Handling”.

Standard exceptions

Python provides the following exceptions:

  1. SyntaxError
  2. ZeroDivisionError
  3. NameError
  4. ValueError
  5. TypeError
  6. IndexError
  7. AttributeError
  8. AssertionError
  9. ImportError etc

(We will discuss the above exceptions in further section briefly).

Raising an Exception

By using raise exception statement you can raise an exception in your own code. Whenever we raise an exception it breaks current code execution and returns the exception back until it is handled.

Ex 1:The below is an example of raising an exception.

>>> def ValueError(Exception):
	pass

>>> raise ValueError
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    raise ValueError
ValueError

Ex 2: Another way to raise an exception by using only a raise statement is as follows:

>>> raise OSError

Traceback (most recent call last):

File “<pyshell#7>”, line 1, in <module>

raise OSError

OSError

>>> raise ValueError

Traceback (most recent call last):

File “<pyshell#8>”, line 1, in <module>

raise ValueError

ValueError

>>> raise AttributeError

Traceback (most recent call last):

File “<pyshell#9>”, line 1, in <module>

raise AttributeError

AttributeError

User-Defined exceptions

In python we are allowed to create our own exceptions with the help of standard built-in exceptions.

We can observe this with the following example. Here the example relates to RunTimeError.

class SudhakarException(Exception):

pass

raise SudhakarException(“this is exception created by sudhakar”)

Output

Traceback (most recent call last):

File “C:\python\exception_userdefined.py”, line 3, in <module>

raise SudhakarException(“this is exception created by sudhakar”)

SudhakarException: this is exception created by sudhakar

Argument of an Exception:

An exception can have an argument, which is a value that provides extra information regarding problem. The contents of the argument vary by exception. You capture an exception’s argument by supplying a variable in the except clause as follows:

Syntax:

try:

You do your operations here

………………….

except ExceptionType as Argument:

The value of Argument can be printed here…

 

 Ex: The following is an example program of an argument of an exception.

x=26
def temp_convert(var):
    try:
        return int(var)
        print(int(var))
    except ValueError as x:
            print("it should accept only integers",x)
print(x)
temp_convert(26)

Output

26

The assert statement:

When it identifies an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises anAssertionError exception.

Syntax:

assert Expression[, Arguments]

Ex:

A=int(input(“enter the value for x”))

assert (A>0),”the value of x should be positive”

Output

enter the value for x -464                                                                #Case 1

Traceback (most recent call last):

File “C:\python\exception_argument.py”, line 25, in <module>

assert (x>0),”the value of x should be positive”

AssertionError: the value of x should be positive

 

 

enter the value for x 464                                                                   #Case 2

>>>

 

 

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest