0% found this document useful (0 votes)
45 views10 pages

Exception Handling

The document discusses different types of programming errors including syntax errors, semantic errors, logical errors, and runtime errors. Syntax errors occur when programs violate the rules of a language's grammar. Semantic errors happen when statements are meaningless. Logical errors stem from flawed reasoning in a program's code. Runtime errors take place during program execution and can include division by zero or referencing a non-existent variable. Exception handling involves anticipating and responding to errors to prevent program crashes.

Uploaded by

Prithvijeet Saha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views10 pages

Exception Handling

The document discusses different types of programming errors including syntax errors, semantic errors, logical errors, and runtime errors. Syntax errors occur when programs violate the rules of a language's grammar. Semantic errors happen when statements are meaningless. Logical errors stem from flawed reasoning in a program's code. Runtime errors take place during program execution and can include division by zero or referencing a non-existent variable. Exception handling involves anticipating and responding to errors to prevent program crashes.

Uploaded by

Prithvijeet Saha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Bug – It is an error in program, it’s something

that prevents a program from compiling or


Exception Handling running correctly.

Sample Code Programming Errors


Broadly programming errors are of three types:
1. Compile/Interpretation time errors
• Syntax errors
• Semantic errors
2. Run time errors
3. Logical errors
Output
Syntax – formal rules governing the construction of valid statements in a language

Semantic – set of rules which gives the meaning of a statement

Sample Code Syntax and Semantic Error


Output Syntax Error:
Error occurred due to not following the proper grammar/syntax of the language, error occurred
due to violating rules of the programming language. Also called as parsing error. On encountering
a syntax error, the interpreter does not execute the program unless we rectify the errors, save
and rerun the program.

Example:
>>>Print(4+5) #should be print
>>>print "Hello" #( ) missing

Semantic Error:
Semantic refers to the set of rules which give the meaning of a statement, and when the
statements are not meaningful the error is semantic error.

Example: X*Y = Z
Logical and Runtime Error A good program is the one that has a code that handles an exception
Logical Error: well i.e. In case an exception occurs, then the exception handling code
Error occurred due to incorrect logic applied by the programmer. written for it will take over and do the necessary action.

If a program doesn’t have an exception handling routine, then in case of


Run Time Error : Error occurring in a program during its execution. Program an exception’s occurrence, the program will halt/crash.
execution halts when such an error is encountered.
Ex. message in ATM machine-
Example: “Not enough amount in the account” is an example of exception handling, in
place of halting of system, exception handling code will display the message
print(5*(1/0)) #division by zero erro and will terminate the code.

Python runtime errors  Each time an error is detected in a program, the Python interpreter
raises (throws) an (specific) exception
• Division by zero error
 Exception handlers code (built-in/userdefined) designed for that
• Performing an operation on incompatible types specific exception executes and handles the error generated
• Using an identifier which has not been defined  Programmers can also forcefully raise exceptions within a program
• Accessing a list element, dictionary value or object using the raise and assert statements
attribute which doesn’t exist
 Once an exception is raised, no further statement in the current block
• Trying to access a file which doesn’t exist of code is executed

 Exception interrupts the normal flow of execution of program and


jumping to the exception handler code

Built-in Exceptions
Exceptions
• Commonly occurring exceptions are usually defined in the
compiler/interpreter. These are called built-in exceptions.
An exception is an error that happens while program is running. It • Python’s standard library is an extensive collection of built-in
interrupts the normal flow of program and indicate that something
exceptions that deals with the commonly occurring errors
unusual has happened in the program.
(exceptions) by providing the standardized solutions for such
errors.
Ex. • On the occurrence of any built-in exception, the appropriate
Entering wrong pin in a ATM machine is an error in user input.
“Not enough amount in the account” is an exception exception handler code is executed which displays the reason
Division by zero is an exception along with the raised exception name.
File not found is an exception
• The programmer then has to take appropriate action to
handle it.
Exception Description
It is raised when there is an error in the syntax of
SyntaxError
the Python code.
Exception Description
Raised when a built-in operation or function IndentationError Raised due to incorrect indentation
ValueError receives and argument with inappropriate type e.g.
int("A123")

IOError Raised when there is a failure of file I/O operation


It is raised when the user accidentally hits the
Delete or Esc key while executing a program due to
KeyboardInterrupt
which the normal flow of the program is
interrupted.
Raised if the requested element doesn’t exist in the
ImportError
module
IndentationError is a type of SyntaxError
Raised when file methods for reading tries to read
EOFError
beyond the file
Raised when division or modulo by zero takes place
ZeroDivisionError
for all numeric types

Exception Description
Raised when an index is not found in a
IndexError
sequence i.e. out of range
NameError Name when an identifier name is not found Exception Description
Raised when a built-in operation or function
IndentationError Raised due to incorrect indentation
ValueError receives and argument with inappropriate
Raised when an operation or function is type e.g. int("A123")
TypeError applied to an object of inappropriate type e.g.
multiplication of two strings
It is raised when the result of a calculation
OverFlowError exceeds the maximum limit for numeric data
type.
Raised when an object does not find an
AttributeError
attribute
Raised when a mapping (dictionary) key is not
KeyError
found in the set of existing keys
Raised when trying to import a module which
ModuleNotFoundError
doesn’t exist

Exception Description Exception Description


It is raised when there is an error in the IOError Raised when there is a failure of file I/O operation
SyntaxError
syntax of the Python code.

FileNotFoundError
and
UnsupportedOperation
Syntax/parsing error is a type of exception which is generated are sub-class of IOError
when the code is syntactically wrong, all other exception will
generate if the code syntactically correct.
Exception Description Exception Description
Raised when file methods for reading tries
It is raised when the user accidentally hits the Delete or EOFError
to read beyond the file
KeyboardInterrupt Esc key while executing a program due to which the
normal flow of the program is interrupted.

Exception Description Exception Description


Raised when trying to import a module Raised when division or modulo by zero
ModuleNotFoundError ZeroDivisionError
which doesn’t exist takes place for all numeric types

Exception Description
Exception Description Raised when an index is not found in a
IndexError
Raised if the requested element doesn’t sequence i.e. out of range
ImportError
exist in the module
Exception Description
Exception Description Raised when an object does not find an
AttributeError
attribute
NameError Name when an identifier name is not found

Exception Description Exception Description


Raised when an operation or function is Raised when a mapping (dictionary) key is
TypeError applied to an object of inappropriate type KeyError
e.g. multiplication of two strings not found in the set of existing keys

Exception Description

OverFlowError
It is raised when the result of a calculation exceeds Raising Exception
the maximum limit for numeric data type.
Apart from built-in exceptions programmers can also
forcefully raise exceptions in a program using the raise
and assert statements
raise statement assert statement
The raise statement can be used to throw an exception. The syntax of An assert statement in Python is used to test an expression in the
raise statement is: program code. If the result after testing comes false, then the exception
is raised.
raise exception-name[(optional argument)]
This statement is generally used in the beginning of the function or
The argument is generally a string that is displayed when the exception is after a function call to check for valid input.
raised, along with a brief description of the error. Ex:
The syntax for assert statement is:

assert Expression[,arguments]

Argument is generally a message.

The error detected may be a built-in exception or may be user-defined. It’s a debugging tool used by software developers.

User-defined raise

Bulit-in exception
handled in raise
Handling Exception
The runtime system searches the entire program for a block of code,
Each and every exception has to be handled by the programmer called the exception handler that can handle the raised exception.
to avoid the program from crashing abruptly.
It first searches for the method in which the error has occurred and
This is done by writing additional code in a program to give the exception has been raised.
proper messages or instructions to the user on encountering an
exception. This process is known as exception handling. If not found, then it searches the method from which this method
(in which exception was raised) was called.
It’s a technique to capture runtime errors and handling them so
as to avoid the program getting crashed. This hierarchical search in reverse order continues till the exception
handler is found. This entire list of methods is known as call stack.

 Python categorises exceptions into distinct types so that specific


exception handlers (code to handle that particular exception) can be When a suitable handler is found in the call stack, it is executed by
created for each type. the runtime process.
 The segment of code which may generate error, is placed inside one
block. This process of executing a suitable handler is known as catching
 The code to handle the error/exception, is placed inside another the exception.
block.
If the runtime system is not able to find an appropriate exception
 These statements for detection and reporting the exception do not after searching all the methods in the call stack, then the program
affect the main logic of the program. execution stops.
 Exception handling can be done for both user-defined and built-in
exceptions.

When an error occurs, Python interpreter creates an object called the


exception object, which stores all details of exception.

The object is handed over to the runtime system so that it can find an
appropriate code to handle this particular exception.

The process of creating an exception object and handing it over to the


runtime system is called throwing an exception.

Imp: During program execution when an exception occurs the control jumps to the exception
handler, abandoning execution of the remaining program statements.
Sometimes, a single piece of code might be suspected to have more
Catching Exceptions than one type of error. For handling such situations, we can have
multiple except blocks for a single try block.
An exception is said to be caught when a code that is designed
to handle a particular exception is executed. When an exception is raised, a search for the matching except block is
made till it is handled. If no match is found, then the program
terminates.

However, if an exception is raised for which no handler is created by


the programmer, then such an exception can be handled by adding an
except clause without specifying any exception. This except clause
should be added as the last clause of the try...except block.

Exception Handling OUTPUT

Exception handling in Python is done through try and except clause,


where the code that may generate and exception is written in the try
block and the code for handling the exception is written in except block.
While executing the program, if an exception is encountered, further
execution of the code inside the try block is stopped and the control is
transferred to the except block.

Syntax:
try: With print(A+B+C)
code that may generate exception
except:
code to handle the exception

Without
print(A+B+C)

Exception Handling in Python


try...except…else clause
Output We can put an optional else clause along with the try...except clause.

An except block will be executed only if some exception is raised in the


try block.

But if there is no error then none of the except blocks will be executed.

In this case, the statements inside the else clause will be executed.
Finally Clause
The try statement in Python can also have an optional finally clause.

The statements inside the finally block are always executed


regardless of whether an exception has occurred in the try block or
not.

It is a common practice to use finally clause while working with files


to ensure that the file object is closed.

If used, finally should always be placed at the end of try clause, after
all except blocks and the else block.

Alternative Code
Recovering and continuing with finally clause To summarise,
Put the piece of code where there are possibilities of errors or
If an error has been detected and is not handled by any of the exceptions to occur inside a try block.
except clauses, then it is re-raised after the execution of the finally
block. Inside each except clause, define handler codes to handle the
matching exception raised in the try block.
Unlike except, execution of the finally clause does not terminate the
exception. Rather, the exception continues to be raised after The optional else clause contains codes to be executed if no exception
execution of finally. occurs.

The optional finally block contains codes to be executed irrespective


of whether an exception occurs or not.

You might also like