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

Errors and Exceptions - in - Python.pptx

  • 2.
    WHAT ARE ERRORSAND 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 Pythonhas 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 WITHTRY 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  tryBlock 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.