- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
What are the best practices for exception handling in Python?
Some of the best practices for exception handling in python are given below:
Exceptions are better than returning error status codes. We have to handle exceptions in Python as the whole language core and standard libraries throw exceptions. Elegantly handled exceptions are any day preferable to error codes and trace backs.
It is wise thing not to use exceptions for flow-control.
Exceptions arise in exceptional situations that are not a part of normal execution.
Consider 'find' on a string returning -1 if the pattern isn't found, but indexing beyond the end of a string raises an exception. Not finding the string is normal execution.
It is better we handle exceptions at the level that we know how to handle them
The best place is that piece of code that can handle the exception. For some exceptions, like programming errors (like IndexError, TypeError, NameError etc.) exceptions are best left to the programmer, because "handling" them may hide real bugs.
Always we should ask "is this the right place to handle this exception?" and be careful with catching all exceptions.
We should document the exceptions thrown by our code. Thinking about which exceptions our code may throw will help us write better, safer and more encapsulated code.
- Related Articles
- C# Exception Handling Best Practices
- What are the best practices for using loops in Python?
- What are the best practices for using if statements in Python?
- What are the “best practices” for using import in a Python module?
- What are the best practices for committing in Git?
- What are Python coding standards/best practices?
- What is exception handling in Python?
- What are the best practices to organize Python modules?
- What are the Best Practices in Visual Marketing?
- Best practices for Java comments.
- Best Practices for Managing the Security Function
- The Best Practices for Client Relationship Management
- What are common practices for modifying Python modules?
- What is exception handling in C#?