Ad Code

Responsive Advertisement

Errors and Exception in Python - 2020 | Tutorial & Notes

Today we will learn what are Errors and Exceptions in Python with their types and How can we Handle them with examples



Errors or Exceptions can occur both in the computer program and in our daily life. And we can handle these Errors using different methods.

Table of Contents

  • What are Errors or Exception?
  • Different Types of Errors in Python
  • Syntax Error 
  • Runtime Error 
  • Exception
  • Standard Exceptions and Their Handling
  • Common Python Exceptions
  • Try and Except Block
  • Multiple Except Statement



Let us understand with a real-life situation

For example, you are coming back from the market in a car and your car tyre gets punctured in this case you carry a spare tyre that you can use in place of a punctured tyre. This is known as Exception Handling.

What are Errors or Exception in Python?


In Python, Exception is the errors that can be solved by  Exception Handling.


Different Types of Errors in Python 

  • Syntax Error
  • Runtime Errors 
  • Exceptions
We will learn all these in detail-:


Syntax Errors

A Syntax Error is an Error in the Syntax of Sequence of Characters and they appear on the screen when we violate the grammatical rule of a Programming Language.

For Example,
If we want to print Hello Wolrd we use a statement which is a print statement and it uses round brackets and quotes which is necessary.

If we do not use round brackets we get the Syntax error you can see it in fig-1.

fig-1

So the right way to print a statement In Python is this -:


print("HELLO WORLD")


Case Sensitive

However, Syntax Errors are hard to find. Python is Case-sensitive, So if you use the wrong case for a variable it will show you a Syntax error.

For example, if you use a print statement with capital P it will give you error which is a Syntax error ( see in fig-2).

fig-2


A few more examples of Syntax errors -:


>>> (4+5]
SyntaxError: closing parenthesis ']' does not match opening parenthesis '('

>>> print 'hello'
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello')?

>>> list [1;2;3]
SyntaxError: invalid syntax

>>> for i in range (10):
print(i)
SyntaxError: expected an indented block

>>> 

Now let us see the reason behind the occurrence of the Syntax Errors.

  • Statement 1 generates an error because of improper closing brackets.
  • Statement 2 generates an error because of missing parenthesis.
  • Statement 3 generates an error because of the semi-colon in place of commas.
  • Statement 4 generates an error because of improper indentation.


Runtime Errors 


A Runtime Error is an error that occurs when the Python interpreter executes the written program.

Runtime Errors come in different types and which are harder to find.


In the above program, Python has given the error instead of the Output.

Some of the Runtime errors are:
  • Division by Zero
  • Performing an operation on incompatible types.
  • Using an identifier which has not been defined. 
  • Trying to access a file that does not exist.
  • Accessing a list, dictionary, or an object attribute that does not exists. 

Exception in Python

Every programming language has some mechanism to handle a program if an error occurs, same as, in Python, we can handle these errors by Exception Handling. Technically an error is termed as an Exception.

Let us discuss some important points related to Exception handling 

1. Exception

An Exception is an error that occurs during the execution of the program and if Exception is not caught than the programs are terminated.

2. Exception Handling 

Python allows us to handle the exception so that the script does not print the error but print a specific code during the exception.

3. Traceback 

The lengthy error message that is shown when the when an exception occurs during the program run.

4. 'Try block' 

Exception Handling in Python is done using try statement. If any error occurs between the statement than the except statement works.

5. 'except for' block or 'catch block'

When error or exception occurs it is handled by the 'except' block.

6. Unhandled, Uncaught exception

An Exception that leads to abnormal termination of a program due to non-execution of an exception thrown is termed as an unhandled or uncaught exception.


Standard Exceptions and Their Handling


When an exception occurs in the program then we say that exception was raised and when we deal with these exceptions then we say that it is handled.

Python provides two statements for Handling an exception in the program-:

  • raise Statement 

1. Raise (raise)  Statement

Raise statement allows the program to give a specified exception to occur at runtime.
Once an exception is raised or thrown it is up to the caller function whether to use try and except statement or propagate further.

Learning Tip:

A raise statement that does not include an exception name will simply re-raise the current exception.

Syntax of raise is:

raise [ exception name [, message / argument ] [,traceback ]]

Here,

Exception name

An exception name is a type of error that can be string, class, or object. It is an instance of an exception class.

Argument

The argument is a value passed to the class.

Traceback

Traceback succeeds in the argument when any exception is raised or thrown.



Common Python Exceptions


  • NameError 
  • TypeError 
  • ValueError 
  • ZeroDivisionError 
  • AttributeError 
  • KeyError
  • IndentationError
  • IOError
  • ImportError
  • EOFError
  • SyntaxError
  • RuntimeError
  • RuntimeError

Let us Study them-:

1. NameError

It raise when the identifier is not found in the local or global namespace.

2. Type error

This type of error is raised when an operation or function is attempted that is invalid for the specified data type.

3. ValueError

This exception is raised when we perform an operation on the incorrect type of Value.

4. ZeroDivisionError

This execution is Rizwan division or modulus by zero takes place for all numeric types.

5. AttributeError

This exception is raised when an object does not find an attribute.


6. KeyError

This error occurs when you access an element of a dictionary using a key that is not present in the dictionary.

7. IndexError

This error occurs when we try to access an index that is out of range.

8. IOError

This error occurs when opening and closing files which do not exist.

9. IndentationError

This error occurs due to incorrect indentation.

The try and except block:

The try and except block in python are used to catch and handle the exceptions. Here, try is the basic part where you put your program and except statement is the response to the exceptions.

First Method-:


try:
   your program here
except:
   If exception then execute this block 


Second Method-:



try:
    your code here
except Exception 1:
    if exception 1 then execute
except Exception 2:
    if exception 2 then execute
else:
    if No exception run this code


Third Method - Finally


To implement some sort of action, Python allows you to clean up after executing the program using finally.


try:
    your code here
except Exception 1:
    if exception 1 then execute
except Exception 2:
    if exception 2 then execute
    ..
    ..
    ..
[else:
    if No exception run this code]
[finally:
    Always executed]


Multiple Except Statment in Python


In Multiple Except statements, we use different except statements for different kinds of exceptions in Python. Using this we can execute different statements for different Exceptions, Let us understand it with Examples.

Example 1 -:



# Try Except and finally clause 

num1=int(input("Enter the Number of times you want to devide"))
for i in range (0,num1,1):
      try:
           a=int(input("Enter the Dividend : "))
           b=int(input("Enter the divisor : "))
           final = a / b
           print(final)
      except ZeroDivisionError: print("Division of 0 not Defined")
      except NameError: print("Variable Not valid")
      except : print("Error Occurred")

Output -:

Enter the Number of times you want to devide2
Enter the Dividend: 40
Enter the divisor : 3
13.333333333333334
Enter the Dividend: 22
Enter the divisor : 0
Division of 0 not Defined


Hope you like this Tutorial on Errors and Exception in Python and if you have any problem in this topic then comment below in the comment section.


Share this tutorial here with your friends,

↓    ↓    ↓    ↓

Post a Comment

0 Comments