Functions, Finally, and Custom Exceptions

0
8Кб

These three concepts are essential for writing robust and maintainable Python code. Here's a breakdown of each:

Functions:

  • Reusable blocks of code that perform a specific task.
  • Defined using the def keyword followed by the function name and parentheses.
  • Can take arguments (inputs) and return values (outputs).
  • Promote code modularity and reusability.

Example:

Python
def greet(name):
  """Prints a greeting message."""
  print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!

Finally:

  • A block of code that always executes, regardless of whether an exception occurs in the try block.
  • Used for essential tasks like closing files or releasing resources.
  • Ensures these tasks are completed even if an error happens.

Example:

Python
try:
  # Code that might raise an exception
  with open("data.txt", "r") as file:
    data = file.read()
except FileNotFoundError:
  print("Error: File not found")
finally:
  # Always executed, even if there's no exception
  print("File closed")

Custom Exceptions:

  • User-defined exceptions to handle specific errors in your program.
  • Inherit from the built-in Exception class.
  • Provide informative error messages and allow for specific handling.

Example:

Python
class InvalidAgeError(Exception):
  """Raised when an invalid age is provided."""
  pass

def check_age(age):
  if age < 0:
    raise InvalidAgeError("Age cannot be negative")
  # Rest of the code

try:
  check_age(-5)
except InvalidAgeError as e:
  print(f"Error: {e}")

Key Points:

  • Functions help organize code and improve readability.
  • finally ensures critical tasks are executed.
  • Custom exceptions provide better error handling and clarity.

By effectively using these concepts, you can write more robust and maintainable Python applications.

Поиск
Категории
Больше
Образование
S.4 CRE PRE-REGISTRATION 2024
https://acrobat.adobe.com/id/urn:aaid:sc:EU:21663e65-af20-41e8-b997-5def68c7399f
От Landus Mumbere Expedito 2024-07-19 23:19:32 0 6Кб
Technology
Steps to Mitigate Cyber Risks
Mitigating cyber risks involves implementing a combination of preventive, detective, and...
От ALAGAI AUGUSTEN 2024-07-15 06:58:01 0 7Кб
Technology
Project Management Software: The Key to Business Growth and Success
Managing multiple projects, teams, and deadlines can be challenging without the right tools....
От Emma Smith 2025-03-03 06:09:10 0 9Кб
Physics
SEPTA-O-LEVEL PHYSICS SEMINAR SLATED FOR 23RD JUNE 2024 AT ST. JOSEPH OF NAZARETH HIGH SCHOOL KAVULE-KATENDE
https://acrobat.adobe.com/id/urn:aaid:sc:EU:39c1aa82-237a-43bf-ba1a-fbe5223d26f1
От Question Bank 2024-07-14 19:52:41 2 10Кб
Образование
The Compromise of 1877
The Compromise of 1877, also known as the Wormley Agreement, the Bargain of 1877, or the Corrupt...
От Modern American History 2024-07-19 05:48:55 0 6Кб
Tebtalks https://tebtalks.com