SlideShare a Scribd company logo
Errors and Exceptions - in - Python.pptx
WHAT ARE ERRORS AND EXCEPTIONS?
 Errors: Mistakes in code that stop it from running or executing.
 Syntax Errors: Wrong code structure (e.g., missing colon).
 Exceptions: Special errors Python can handle during runtime.
 Problems during execution (e.g., dividing by zero).
 Example: Trying to open a missing file raises a FileNotFoundError.
 Why Care? Handling exceptions makes programs reliable and user-friendly.
TYPES OF ERRORS
 Syntax Errors: Code breaks Python’s rules.
 Caused by incorrect language syntax (parsing errors)
print("Hello) # Missing quote → SyntaxError
 Exceptions: Hard to spot;
 Happen when code runs, at runtime after passing syntax checks.
x = 10 / 0 # Division by zero → ZeroDivisionError
COMMON BUILT-IN EXCEPTIONS
Python has many built-in exceptions for specific issues:
 ZeroDivisionError: Dividing by zero (e.g., 10 / 0).
 TypeError: Wrong data type (e.g., "2" + 3).
 NameError: Using undefined variable (e.g., print(x) before defining x).
 FileNotFoundError: Opening a missing file (e.g., open("data.txt")).
 IndexError: Accessing invalid list index (e.g., lst = [1, 2]; lst[5]).
 Check Them: Use dir(__builtins__) to see all built-in exceptions.
HANDLING EXCEPTIONS WITH TRY EXCEPT
Use try and except to catch and handle exceptions:
 try:
num = int(input("Enter a number: "))
result = 10 / num print("Result:", result)
 except ZeroDivisionError:
print("Error: Cannot divide by zero!")
 except ValueError:
print("Error: Please enter a valid number!")
 How It Works:
 try: Run risky code.
 except: Handle specific errors.
 else: Runs if no error (e.g.,
print("Success!")).
 finally: Always runs (e.g., to close a file).
 Example Output:
 Input 0 → "Error: Cannot divide by zero!"
 Input "abc" → "Error: Please enter a valid
number!"
UNDERSTANDING TRY-EXCEPT-ELSE-FINALLY
 try Block
This is where you put your code that might cause an error. If an error occurs, Python jumps to
the except block.
 except Block
This is where you handle the error. You can specify the type of error or catch any exception.
 else Block (optional)
This runs only if no exception occurs in the try block. It helps separate normal code from
exception handling.
 finally Block (optional)
This block always runs—whether an exception occurs or not. It’s used for cleanup tasks like
closing a file or releasing resources.
 try:
num = int(input("Enter a number: "))
result = 10 / num # Might cause
ZeroDivisionError
 except ZeroDivisionError:
print("Oops! Division by zero is not allowed.")
 except ValueError:
print("Invalid input! Please enter a valid
number.")
 else:
print(f"Success! Your result is {result}")
 finally:
print("Execution complete. Thanks for using our
program!")
How It Works:
 If the user enters “0”, it triggers
‘ZeroDivisionError’, which is handled “except”.
 If they enter “abc”, it triggers ‘ValueEror’,
which is also handled
 If they enter “5”, the ‘else’ block runs smoothly
with the calculation.
 Regardless of what happens, the ‘finally’ block
runs every time
This helps prevent our program from crashing
unexpectedly.
Errors and Exceptions - in - Python.pptx

More Related Content

PDF
Python programming : Exceptions
PPTX
Error and exception in python
PPTX
Mastering Errors and Exceptions in Python: A Comprehensive Guide
PDF
Wondershare UniConverter Crack FREE Download 2025 version
PPTX
Python Lecture 7
PDF
Unit 4-Exception Handling in Python.pdf
PPTX
Exception Handling in python programming.pptx
PPT
Exception Handling on 22nd March 2022.ppt
Python programming : Exceptions
Error and exception in python
Mastering Errors and Exceptions in Python: A Comprehensive Guide
Wondershare UniConverter Crack FREE Download 2025 version
Python Lecture 7
Unit 4-Exception Handling in Python.pdf
Exception Handling in python programming.pptx
Exception Handling on 22nd March 2022.ppt

Similar to Errors and Exceptions - in - Python.pptx (20)

PPTX
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
PPTX
Exception Handling.pptx
PPTX
Python Exception Handling
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
PPTX
Exception Handling in Python topic .pptx
DOCX
Exception handlingpdf
PPTX
exceptioninpython.pptx
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
PPTX
Python Exceptions Powerpoint Presentation
PPTX
LECT 29- EXCEPTION HANDLING.pptx b.
PPTX
Exception Handling in Python Programming.pptx
PPTX
Exception Handling in Python programming.pptx
PPT
Exception handling in python and how to handle it
PPTX
Python Exception handling using Try-Except-Finally
PPTX
Exception handling.pptx
PPT
PPT
Exception Handling using Python Libraries
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
Exception Handling.pptx
Python Exception Handling
lecs101.pdfgggggggggggggggggggddddddddddddb
Exception Handling in Python topic .pptx
Exception handlingpdf
exceptioninpython.pptx
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
Python Exceptions Powerpoint Presentation
LECT 29- EXCEPTION HANDLING.pptx b.
Exception Handling in Python Programming.pptx
Exception Handling in Python programming.pptx
Exception handling in python and how to handle it
Python Exception handling using Try-Except-Finally
Exception handling.pptx
Exception Handling using Python Libraries
Ad

More from Vignan's Foundation for Science, Technology and Research (Deemed to be University) (9)

Ad

Recently uploaded (20)

PPTX
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
PDF
Introduction to Data Science and Data Analysis
PPT
Predictive modeling basics in data cleaning process
PPTX
Business_Capability_Map_Collection__pptx
PPT
statistic analysis for study - data collection
PPTX
A Complete Guide to Streamlining Business Processes
PDF
Tetra Pak Index 2023 - The future of health and nutrition - Full report.pdf
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
PPTX
IMPACT OF LANDSLIDE.....................
PDF
Global Data and Analytics Market Outlook Report
PDF
Systems Analysis and Design, 12th Edition by Scott Tilley Test Bank.pdf
PPTX
Topic 5 Presentation 5 Lesson 5 Corporate Fin
PPTX
chrmotography.pptx food anaylysis techni
PPTX
FMIS 108 and AISlaudon_mis17_ppt_ch11.pptx
PDF
Microsoft 365 products and services descrption
PPTX
Copy of 16 Timeline & Flowchart Templates – HubSpot.pptx
PPTX
Introduction to Inferential Statistics.pptx
PPTX
SET 1 Compulsory MNH machine learning intro
PDF
Optimise Shopper Experiences with a Strong Data Estate.pdf
PPTX
Steganography Project Steganography Project .pptx
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
Introduction to Data Science and Data Analysis
Predictive modeling basics in data cleaning process
Business_Capability_Map_Collection__pptx
statistic analysis for study - data collection
A Complete Guide to Streamlining Business Processes
Tetra Pak Index 2023 - The future of health and nutrition - Full report.pdf
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
IMPACT OF LANDSLIDE.....................
Global Data and Analytics Market Outlook Report
Systems Analysis and Design, 12th Edition by Scott Tilley Test Bank.pdf
Topic 5 Presentation 5 Lesson 5 Corporate Fin
chrmotography.pptx food anaylysis techni
FMIS 108 and AISlaudon_mis17_ppt_ch11.pptx
Microsoft 365 products and services descrption
Copy of 16 Timeline & Flowchart Templates – HubSpot.pptx
Introduction to Inferential Statistics.pptx
SET 1 Compulsory MNH machine learning intro
Optimise Shopper Experiences with a Strong Data Estate.pdf
Steganography Project Steganography Project .pptx

Errors and Exceptions - in - Python.pptx

  • 2. WHAT ARE ERRORS AND EXCEPTIONS?  Errors: Mistakes in code that stop it from running or executing.  Syntax Errors: Wrong code structure (e.g., missing colon).  Exceptions: Special errors Python can handle during runtime.  Problems during execution (e.g., dividing by zero).  Example: Trying to open a missing file raises a FileNotFoundError.  Why Care? Handling exceptions makes programs reliable and user-friendly.
  • 3. TYPES OF ERRORS  Syntax Errors: Code breaks Python’s rules.  Caused by incorrect language syntax (parsing errors) print("Hello) # Missing quote → SyntaxError  Exceptions: Hard to spot;  Happen when code runs, at runtime after passing syntax checks. x = 10 / 0 # Division by zero → ZeroDivisionError
  • 4. COMMON BUILT-IN EXCEPTIONS Python has many built-in exceptions for specific issues:  ZeroDivisionError: Dividing by zero (e.g., 10 / 0).  TypeError: Wrong data type (e.g., "2" + 3).  NameError: Using undefined variable (e.g., print(x) before defining x).  FileNotFoundError: Opening a missing file (e.g., open("data.txt")).  IndexError: Accessing invalid list index (e.g., lst = [1, 2]; lst[5]).  Check Them: Use dir(__builtins__) to see all built-in exceptions.
  • 5. HANDLING EXCEPTIONS WITH TRY EXCEPT Use try and except to catch and handle exceptions:  try: num = int(input("Enter a number: ")) result = 10 / num print("Result:", result)  except ZeroDivisionError: print("Error: Cannot divide by zero!")  except ValueError: print("Error: Please enter a valid number!")  How It Works:  try: Run risky code.  except: Handle specific errors.  else: Runs if no error (e.g., print("Success!")).  finally: Always runs (e.g., to close a file).  Example Output:  Input 0 → "Error: Cannot divide by zero!"  Input "abc" → "Error: Please enter a valid number!"
  • 6. UNDERSTANDING TRY-EXCEPT-ELSE-FINALLY  try Block This is where you put your code that might cause an error. If an error occurs, Python jumps to the except block.  except Block This is where you handle the error. You can specify the type of error or catch any exception.  else Block (optional) This runs only if no exception occurs in the try block. It helps separate normal code from exception handling.  finally Block (optional) This block always runs—whether an exception occurs or not. It’s used for cleanup tasks like closing a file or releasing resources.
  • 7.  try: num = int(input("Enter a number: ")) result = 10 / num # Might cause ZeroDivisionError  except ZeroDivisionError: print("Oops! Division by zero is not allowed.")  except ValueError: print("Invalid input! Please enter a valid number.")  else: print(f"Success! Your result is {result}")  finally: print("Execution complete. Thanks for using our program!") How It Works:  If the user enters “0”, it triggers ‘ZeroDivisionError’, which is handled “except”.  If they enter “abc”, it triggers ‘ValueEror’, which is also handled  If they enter “5”, the ‘else’ block runs smoothly with the calculation.  Regardless of what happens, the ‘finally’ block runs every time This helps prevent our program from crashing unexpectedly.