Exception Handling in Python Part 1

Exception Handling in Python


What is an Exception?

An exception is an error that happens during execution of a program. When that error occurs, Python generate an exception that can be handled, which avoids your program to crash.

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

Python has many built-in exceptions which forces your program to output an error when something in it goes wrong.

When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash.

For example, if function A calls function B which in turn calls function C and an exception occurs in function C. If it is not handled in C, the exception passes to B and then to A.

If never handled, an error message is spit out and our program comes to a sudden, unexpected halt

 

Exception Errors


Below are some common exceptions errors in Python:

IOError
If the file cannot be opened.

ImportError
If python cannot find the module

ValueError
Raised when a built-in operation or function receives an argument that has
the right type but an inappropriate value

KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

Syntax:

try:
    some statements here
except:
    exception handling

try:
   # do something
   pass

except ValueError:
   # handle ValueError exception
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except:
   # handle all other exceptions
   pass

If no exception occurs, except block is skipped and normal flow continues. But if any exception occurs, it is caught by the except block.

Raising an Exception

You can raise an exception in your own program by using the raise exception statement.

Raising an exception breaks current code execution and returns the exception back until it is handled.

Example:
try:
    a = int(input("Enter a positive integer: "))
    if a <= 0:
        raise ValueError("Opps! That is not a positive number!")
    print("You Enter : ", a)
except ValueError as ve:
    print(ve)

OR

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

 

Try ... except ... else clause


The else clause in a try, except statement must follow all except clauses, and is useful for code that must be executed if the try clause does not raise an exception.

try:
    data = something_that_can_go_wrong
 
except IOError:
    handle_the_exception_error
 
else:
    doing_different_exception_handling

 

Try ... finally clause

 

The finally clause is optional. It is intended to define clean-up actions that must be executed under all circumstances. A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.



Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes