Skip to main content

Python Try Except

 

Python Try Except




The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.


Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement:

Example

The try block will generate an exception, because x is not defined:

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

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example

This statement will raise an error, because x is not defined:

print(x)


Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

Example

Print one message if the try block raises a NameError and another for other errors:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")



Else

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example

In this example, the try block does not generate any error:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")


Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Example

Try to open and write to a file that is not writable:

try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()

The program can continue, without leaving the file object open.


Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")

Comments

Popular posts from this blog

Python Introduction

  Python  Introduction What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: web development (server-side), software development, mathematics, system scripting. What can Python do? Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development. Why Python? Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototypin

LIST OF TOPICS YOU WILL BE LEARN THIS WHOLE SERIES

Python  Introduction    Python  Getting Started Python  Variables Python  Comments Python Try Except Python Data Types Python Casting Python Strings Python Operators Python Lists Python Tuples Python Sets Python Dictionaries Python Arrays Python PIP Python Booleans Python If  Else Python Loops Python Functions Python Lambda Function Python Modules Python Random Module Python cmath Module Python Math Module Python Classes and Objects Python Inheritance PYTHON FILE I/O                Video Contain 1. Telusko 2. CodeWithHarry For Certification Course 01. Udemy1 02. Udemy2                                                                                                                                          NEXT>

Python Getting Started

  Python  Getting Started Python Install Many PCs and Macs will have python already installed. To check if you have python installed on a Windows PC, search in the start bar for Python or run the following on the Command Line (cmd.exe): C:\Users\ Your Name >python --version To check if you have python installed on a Linux or Mac, then on linux open the command line or on Mac open the Terminal and type: python --version If you find that you do not have python installed on your computer, then you can download it for free from the following website:  https://www.python.org/ Python Quickstart Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed. The way to run a python file is like this on the command line: C:\Users\ Your Name >python helloworld.py Where "helloworld.py" is the name of your python file. Let's write our first Python fi