Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

Exception Handling with Strings

in Python
Understanding and Managing String-
Related Errors
Your Name
Date
What is Exception Handling?
• • Definition of exceptions
• • Importance of exception handling
• • Common scenarios where exceptions occur
Common String-Related Exceptions
• • ValueError
• • TypeError
• • IndexError
• • KeyError
The Try-Except Block
• Syntax of try-except:
• ```
• try:
• # code that may cause an exception
• except ExceptionType:
• # code that runs if the exception occurs
• ```
Handling ValueError
• Example of ValueError with strings:
• ```
• try:
• int("abc")
• except ValueError as e:
• print(f"ValueError: {e}")
• ```
Handling TypeError
• Example of TypeError with strings:
• ```
• try:
• "abc" + 123
• except TypeError as e:
• print(f"TypeError: {e}")
• ```
Handling IndexError
• Example of IndexError with strings:
• ```
• try:
• s = "abc"
• print(s[5])
• except IndexError as e:
• print(f"IndexError: {e}")
• ```
Handling KeyError
• Example of KeyError with strings in a
dictionary:
• ```
• try:
• d = {"key1": "value1"}
• print(d["key2"])
• except KeyError as e:
• print(f"KeyError: {e}")
• ```
Using Finally Block
• Explanation of the finally block:
• ```
• try:
• # code that may cause an exception
• except ExceptionType:
• # code that runs if the exception occurs
• finally:
• # code that runs no matter what
• ```
Raising Exceptions
• How to raise an exception:
• ```
• if not isinstance(value, str):
• raise TypeError("Value must be a string")
• ```
Custom Exceptions
• Creating a custom exception:
• ```
• class MyCustomError(Exception):
• pass

• try:
• raise MyCustomError("An error occurred")
• except MyCustomError as e:
• print(f"MyCustomError: {e}")
Conclusion
• • Recap of key points
• • Importance of handling exceptions properly
• • Encouragement to practice with examples
Questions and Answers
• Open floor for questions
References
• • Links to Python documentation and other
resources
Multiple Choice Question 1
• What exception will be raised by the following
code?
• ```
• int("123abc")
• ```
• A) TypeError
• B) ValueError
• C) IndexError
• D) KeyError
Multiple Choice Question 2
• Which block is executed no matter whether an
exception occurs or not?
• A) try
• B) except
• C) finally
• D) raise

• Answer: C) finally

You might also like