• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Error Handling / Try and Except in Python

Try and Except in Python

Author: PFB Staff Writer
Last Updated: May 20, 2020

Earlier I wrote about Errors and Exceptions in Python. This post will be about how to handle those. Exception handling allows us to continue our program (or terminate it) if an exception occurs.

Error Handling

Error handling in Python is done through the use of exceptions that are caught in try blocks and handled in except blocks.

Try and Except

If an error is encountered, a try block code execution is stopped and transferred down to the except block.

In addition to using an except block after the try block, you can also use the finally block.

The code in the finally block will be executed regardless of whether an exception occurs.

Raising an Exception

You can raise an exception in your own program by using the raise exception [, value] statement.

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

Example

A try block look like below

try:
    print "Hello World"
except:
    print "This is an error message!"

Exception Errors

Some of the common exception errors are:

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

Example

Let’s have a look at some examples using exceptions.

except IOError:
    print('An error occured trying to read the file.')
    
except ValueError:
    print('Non-numeric data found in the file.')

except ImportError:
    print "NO module found"
    
except EOFError:
    print('Why did you do an EOF on me?')

except KeyboardInterrupt:
    print('You cancelled the operation.')

except:
    print('An error occured.')

There are a number of built-in exceptions in Python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Error Handling Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us