Functions, Finally, and Custom Exceptions

0
11Кб

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.

Поиск
Категории
Больше
Business
Business Success is a Marathon, Not a Sprint
Strategies for Thriving in Today’s Fast-Paced Environment In the fast-paced world of...
От ALAGAI AUGUSTEN 2024-08-03 15:39:53 0 11Кб
Computer Programming
Adding comments in HTML (<!-- comment -->)
While global attributes can be applied to any HTML element, some attributes are specific to...
От HTML PROGRAMMING LANGUAGE 2024-08-15 01:50:21 0 8Кб
Physics
QUANTUM PHYSICS
Quantum mechanics 
От PHYSICS FOR MASTER'S STUDENTS 2024-08-31 05:11:54 0 12Кб
Computer Programming
HTML Paragraphs (<p>)
HTML paragraphs are defined by the <p> tag. They are used to group related sentences or...
От HTML PROGRAMMING LANGUAGE 2024-08-15 01:19:42 0 8Кб
Technology
Understanding the MOD Function
The MOD function in Excel is used to find the remainder after a number is divided by a divisor....
От Microsoft Excel 2024-09-03 03:27:42 2 12Кб
Tebtalks https://forum.tebtalks.com