SlideShare uma empresa Scribd logo
1 de 20
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 7
Fundamentals of Programming
Python Errors and Exceptions
We can make certain mistakes while writing a program that lead
to errors when we try to run it.
A python program terminates as soon as it encounters an
unhandled error.
These errors can be broadly classified into two classes:
• Syntax errors
• Logical errors (Exceptions)
Python Syntax Errors
Error caused by not following the proper structure (syntax) of the
language is called syntax error or parsing error
if a < 3
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax
Exceptions
Errors that occur at runtime (after passing the syntax test) are
called exceptions or logical errors
For instance, they occur when we try to open a file(for reading)
that does not exist (FileNotFoundError),
,when trying to divide a number by zero (ZeroDivisionError),
or try to import a module that does not exist (ImportError)
Whenever these types of runtime errors occur,
Python creates an exception object. If not handled properly, it
prints a traceback to that error along with some details about why
that error occurred
1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory:
'imaginary.txt'
Built-in Exceptions
Illegal operations can raise exceptions.
There are plenty of built-in exceptions in Python
print(dir(locals()['__builtins__']))
Try Catch
Python Exceptions can be handled using try catch block
If there is no try catch block, python will try stops the current
process and passes it to the calling process until it is handled. If
not handled, the program will crash.
Try Catch
In Python, exceptions can be handled using a try statement
The critical operation which can raise an exception is placed
inside the try clause
The code that handles the exceptions is written in the except
clause
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number.
Try again")
In this program, we are expecting the user to input a number
If the user does not enters a number then a ValueError exception
will be raised
Exception Class
def this_fails():
x = 1/0
try:
this_fails()
except Exception as err:
print('Handling run-time error:', err)
Catching Specific Exceptions
A try clause can have any number of except clauses to handle
different exceptions, however, only one will be executed in case an
exception occurs
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as err:
print(Divide By Zero Error:', err)
try:
# Try
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
Raising Exceptions in Python
In Python programming, exceptions are raised when errors occur at runtime.
We can also manually raise exceptions using the raise keyword
>> raise KeyboardInterrupt
Traceback (most recent call last):
KeyboardInterrupt
>> raise MemoryError("This is an argument")
Traceback (most recent call last):
MemoryError: This is an argument
try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise ValueError("That is not a positive
number!")
except ValueError as ve:
print(ve)
Enter a positive integer: -2
That is not a positive number!
Else in try catch
In some situations, you might want to run a certain block of code if the code
block inside try ran without any errors.
For these cases, you can use the optional else keyword with the try
statement
try:
f = open('filename.txt','r')
except Exception as e:
print('Some exception in opening the file')
else:
f.close()
Python finally block
The try statement in Python can have an optional finally clause.
This clause is executed no matter what, and is generally used to
release external resources
For example, we may be connected to a remote data center
through the network or working with a file or a Graphical User
Interface (GUI)
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Mastering Python lesson 3a
Mastering Python lesson 3aMastering Python lesson 3a
Mastering Python lesson 3a
 
While loop
While loopWhile loop
While loop
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
Lesson1 python an introduction
Lesson1 python an introductionLesson1 python an introduction
Lesson1 python an introduction
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
 
Mastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsMastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loops
 
Python Session - 5
Python Session - 5Python Session - 5
Python Session - 5
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTES
 
Mastering python lesson2
Mastering python lesson2Mastering python lesson2
Mastering python lesson2
 
Python Session - 2
Python Session - 2Python Session - 2
Python Session - 2
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
Python basics
Python basicsPython basics
Python basics
 
Python made easy
Python made easy Python made easy
Python made easy
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 

Semelhante a Python Lecture 7

Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
EXCEPTION HANDLING IN PYTHON For students .py.pptx
EXCEPTION  HANDLING IN PYTHON For students .py.pptxEXCEPTION  HANDLING IN PYTHON For students .py.pptx
EXCEPTION HANDLING IN PYTHON For students .py.pptx
MihirBhardwaj3
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

Semelhante a Python Lecture 7 (20)

Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
 
exceptioninpython.pptx
exceptioninpython.pptxexceptioninpython.pptx
exceptioninpython.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
Exception handling
Exception handlingException handling
Exception handling
 
EXCEPTION HANDLING IN PYTHON For students .py.pptx
EXCEPTION  HANDLING IN PYTHON For students .py.pptxEXCEPTION  HANDLING IN PYTHON For students .py.pptx
EXCEPTION HANDLING IN PYTHON For students .py.pptx
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.ppt
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 

Mais de Inzamam Baig

Mais de Inzamam Baig (13)

Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Lecture 10
Python Lecture 10Python Lecture 10
Python Lecture 10
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
 

Último

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

Python Lecture 7

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 7 Fundamentals of Programming
  • 2. Python Errors and Exceptions We can make certain mistakes while writing a program that lead to errors when we try to run it. A python program terminates as soon as it encounters an unhandled error. These errors can be broadly classified into two classes: • Syntax errors • Logical errors (Exceptions)
  • 3. Python Syntax Errors Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error if a < 3 File "<interactive input>", line 1 if a < 3 ^ SyntaxError: invalid syntax
  • 4. Exceptions Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors For instance, they occur when we try to open a file(for reading) that does not exist (FileNotFoundError), ,when trying to divide a number by zero (ZeroDivisionError), or try to import a module that does not exist (ImportError)
  • 5. Whenever these types of runtime errors occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred
  • 6. 1 / 0 Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> ZeroDivisionError: division by zero open("imaginary.txt") Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
  • 7. Built-in Exceptions Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python print(dir(locals()['__builtins__']))
  • 8. Try Catch Python Exceptions can be handled using try catch block If there is no try catch block, python will try stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.
  • 9. Try Catch In Python, exceptions can be handled using a try statement The critical operation which can raise an exception is placed inside the try clause The code that handles the exceptions is written in the except clause
  • 10. while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again")
  • 11. In this program, we are expecting the user to input a number If the user does not enters a number then a ValueError exception will be raised
  • 12. Exception Class def this_fails(): x = 1/0 try: this_fails() except Exception as err: print('Handling run-time error:', err)
  • 13. Catching Specific Exceptions A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs try: # do something pass except ValueError: # handle ValueError exception pass
  • 14. def this_fails(): x = 1/0 try: this_fails() except ZeroDivisionError as err: print(Divide By Zero Error:', err)
  • 15. try: # Try except (TypeError, ZeroDivisionError): # handle multiple exceptions # TypeError and ZeroDivisionError pass
  • 16. Raising Exceptions in Python In Python programming, exceptions are raised when errors occur at runtime. We can also manually raise exceptions using the raise keyword >> raise KeyboardInterrupt Traceback (most recent call last): KeyboardInterrupt >> raise MemoryError("This is an argument") Traceback (most recent call last): MemoryError: This is an argument
  • 17. try: a = int(input("Enter a positive integer: ")) if a <= 0: raise ValueError("That is not a positive number!") except ValueError as ve: print(ve) Enter a positive integer: -2 That is not a positive number!
  • 18. Else in try catch In some situations, you might want to run a certain block of code if the code block inside try ran without any errors. For these cases, you can use the optional else keyword with the try statement try: f = open('filename.txt','r') except Exception as e: print('Some exception in opening the file') else: f.close()
  • 19. Python finally block The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources For example, we may be connected to a remote data center through the network or working with a file or a Graphical User Interface (GUI)
  • 20. try: f = open("test.txt",encoding = 'utf-8') # perform file operations finally: f.close()

Notas do Editor

  1. We can view all the built-in exceptions using the built-in local() function
  2. or example, let us consider a program where we have a function A that calls function B, which in turn calls function C. If an exception occurs in function C but is not handled in C, the exception passes to B and then to A
  3. we print the name of the exception using the exc_info() function inside sys module. We can see that a causes ValueError and 0 causes ZeroDivisionError
  4. We can use a tuple of values to specify multiple exceptions in an except clause