Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (86 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

What is Try Except in Python and how it works?

Published on Oct 16,2019 5K Views

10 / 62 Blog from Python Fundamentals

No matter how good you are at programming, there will be errors in certain scripts. These errors might occur because of unexpected user input, an erroneous server response or any other reason. Try Except in Python allows you to catch errors and, instead of dying, do something more reasonable. In this article, we will see how Python uses the try-except to handle the exception in the following sequence:

What is Try Except in Python?

The Try method is used in Error and Exception Handling. There are two kinds of errors :

  • Syntax Error: It is also known as Parsing Error. This occurs when the Python parser is unable to understand a line of code.

  • Exception Error: These errors are detected during execution.

Now, in these situations, we need to handle these errors within our code in Python. That is where try-except in python comes handy.

Syntax:

try:
// Code
except:
// Code

Example:

try:
print(x)
except:
print("An exception occurred")

Output:

Output: try except in python - edureka

 

How Does Try() Work?

The different steps involved in the working of try are:

  • The try clause is executed between the try and except clause.
  • If there is no exception, then only the try clause will run and except clause is finished.
  • The try clause will be skipped and except clause will run if any exception occurs.
  • In case of any exception, if the except clause within the code doesn’t handle it, it is passed on to the outer try statements. The execution is stopped if the exception left unhandled.
  • A try statement can have more than one except clause.

 

Python Exceptions Example

In the first example, there is no exception, so the try clause will run:

def divide(x, y):
try:
result = x // y
print("The answer is :", result)
except ZeroDivisionError:
print("Sorry ! Cannot divide by zero ")
divide(10, 5)

Output:

The answer is : 2

In the second example, there is an exception so only except clause will run:

def divide(x, y):
try:
result = x // y
print("The answer is :", result)
except ZeroDivisionError:
print("Sorry ! Cannot divide by zero ")
divide(4, 0)

Output:

Sorry ! Cannot divide by zero

 

Exception Handling

The try and except block in Python is used to catch and handle exceptions. Python executes a code considering the try statement as a normal part of the program. Whereas, the except statement acts as the program’s response to any exceptions in the preceding try clause.

Exceptions are convenient for handling errors and special conditions in a program. If you are working with a code that can produce an error then you can use exception handling. Also, 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.

 

Exception Errors

There are different types of Exception Errors such as:

  • IOError: If the file cannot be opened
  • KeyboardInterrupt: When an unrequired key is pressed by the user
  • ValueError: When the built-in function receives a wrong argument
  • EOFError: If End-Of-File is hit without reading any data
  • ImportError: If it is unable to find the module

With this, we have come to the end of our article. I hope you understood what is try except in Python and how it is used for handling exceptions.

To get in-depth knowledge of Python along with its various applications, you can enroll for live Python Certification Training with 24/7 support and lifetime access. 

Got a question for us? Please mention it in the comments section of this “try except in Python” blog and we will get back to you as soon as possible.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 30th November,2024

30th November

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
Comments
1 Comment
  • HI,
    Its very nice article which helped me to learn python exception. very well explained I really enjoy reading all your blogs which contains all the information which is needed to learn to get a job and make career in it.

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is Try Except in Python and how it works?

edureka.co