Skip to main content

Python Exceptions Handling

Python Exceptions Handling

As in the beginning of this tutorial we have studied about the types of errors that occur in a program. Sometime we what to catch some or all errors that can possibly get generated; and as a programmer we want to be as specific as possible. So, python allows programmers to deal with errors smoothly.
Exceptions are events that are used to modify the flow of control through a program when the error occurs. Exceptions get triggered automatically on finding errors in Python.
These exceptions are processed using five statements. These are:
  1. try/except: catch the error and recover from exceptions hoist by programmers or Python itself.
  2. try/finally: Whether exception occurs or not, it automatically performs the clean-up action.
  3. assert: triggers an exception conditionally in the code.
  4. raise: manually triggers an exception in the code.
  5. with/as: implement context managers in older versions of Python such as – Python 2.6 & Python 3.0.
The last was an optional extension until Python 2.6 & Python 3.0.

Why Exceptions Are Used?

Exceptions allow us to jump out of random illogical large chunks of codes in case of errors. Let us take a scenario that you have given a function to do a specific task. If you go there and found those things missing that are required to do that specific task, what will you do? Either you stop working or think about a solution – where to find those items to perform the task. Same thing happens here in case of Exceptions also. Exceptions allow programmers jump to an exception handler in a single step, abandoning all function calls. You can think exceptions like an optimized quality go-to statement, in which the program error that occurs at runtime gets easily managed by the exception block. When the interpreter encounters error, it lets the execution go to the exception part to solve and continue the execution instead of stopping.
While dealing with exceptions, the exception handler creates a mark & executes some code. Somewhere further within that program the exception is raised that solves the problem & makes Python jump back to the marked location; by not throwing away/skipping any active functions that were called after the marker was left.

Roles Of An Exception Handler In Python

  • Error handling: The exceptions get raised whenever Python detects an error in program at runtime. As a programmer, if you don’t want the default behavior then code a ‘try’ statement to catch and recover a program from an exception. Python will jump to the ‘try’ handler when the program detects an error the execution will be resumed.
  • Event Notification: Exceptions are also used to signal suitable conditions & then passing result flags around a program & text them explicitly.
  • Terminate Execution: There may arise some problems or errors in programs that it needs a termination. So try/finally is used that guarantees that closing-time operation will be performed. The ‘with’ statement offers alternative for objects that support it.
  • Exotic flow of Control: Programmers can also use exceptions as a basis for implementing unusual control flow. Since there is no ‘go to’ statement in Python so exceptions can help in this respect.

A Simple Program To Demonstrate Python Exception Handling

Example 01:
#!/usr/bin/python

(a,b) = (6,0)
try: # simple use of try-except block for handling errors
g
= a/b
except ZeroDivisionError:
print ("This is a DIVIDED BY ZERO error")
The above program can also be written like this:
Example 02:
#!/usr/bin/python
(a,b) = (6,0)
try:
g
= a/b
except ZeroDivisionError as s:
k
= s
print (k)
#Output will be: integer division or modulo by zero

The ‘try – Except’ Clause With No Exception

The structure of such type of ‘except’ clause having no exception is shown with an example.
#!/usr/bin/python
try:
# all operations are done within this block.
. . . . . .
except:
# this block will get executed if any exception encounters.
. . . . . .
else:
# this block will get executed if no exception is found.
. . . . . .
All the exceptions get caught where there is try/except statement of this type. Good programmers use this technique of exception to make program fully executable.

‘except’ Clause With Multiple Exceptions

#!/usr/bin/python

try:
# all operations are done within this block.
. . . . . .
except ( Exception1 [, Exception2[,….Exception N ] ] ] ) :
# this block will get executed if any exception encounters from the above lists of exceptions.
. . . . . .
else:
# this block will get executed if no exception is found.
. . . . . .

The ‘try – Finally’ Clause

#!/usr/bin/python

try:
# all operations are done within this block.
. . . . . .
# if any exception encounters, this block may get skipped.
finally:
. . . . . .
# this block will definitely be executed.

Comments

For Programs Click Here

Popular posts from this blog

Syllabus

Syllabus  C Programming Tutorials C Tutorial C Introduction History of C Programming Language C Installation C Program Structure C Input and Output (I/O) C Format Specifiers Declaration & Assignments C Tokens C Identifiers C Keywords C Constants C Operators C Data Types C Variables C Preprocessors C Type Casting C Custom Header File Flow Control C Decision Making C if Statements C if-else Statements C Nested if-else Statements C else-if Statements C goto Statement C switch Statements C Loops C while loops C do while loops C for loops Functions C Functions C Function Arguments C Library Functions C Variable Scope Arrays & Strings C Arrays C Strings Pointers C Pointers C Dynamic Memory Allocation Structure & Union C Structures C Unions File I/O C File Handling C fopen C fclose C getc C putc C getw C putw C fprintf C fscanf C fgets C fputs C feof                                     ...

Syllabus

Python Tutorials Python Tutorial Python Overview Python Installation Basics of Python Programming Python Operators Python Keywords Python Numbers Python Strings Python Data Types Python Variables Python Lists Python Tuples Python Date and Time Python Decision Making Python Loops Python File Handling Python Dictionaries Python Functions Python Modules Python Exceptions Handling Python Object Oriented Inheritance in Python Python Regular Expressions Python Networking Programming Python Multithreaded Programming Python CGI Programming Python Database Connection Python Metaprogramming Python Data Processing And Encoding Python GUI Programming

Java Method Overriding

Java Method Overriding Declaring a method in the subclass which already exists there in the parent class is known as method overriding. When a class is inheriting a method from a superclass of its own, then there is an option of overriding the method provided it is not declared as final. The advantage of using overriding is the ability to classify a behavior that’s specific to the child class and the child class can implement a parent class method based on its necessity. There are certain rules that a programmer should follow in order to implement overriding. These are: In Java, a method can only be written in the child class and not in same class. Argument list should be exactly the same as that of the overridden method of that class. Instance methods can also be overridden if they are inherited by the child class. A constructor cannot be overridden. Final – declared methods cannot be overridden. Any method that is static cannot be used to override. The return type must have to be the...