Skip to content

Commit 185a421

Browse files
Ksound22Dario-DC
andauthored
feat(curriculum): add Python error handling review page (freeCodeCamp#60559)
Co-authored-by: Dario <105294544+Dario-DC@users.noreply.github.com>
1 parent 922c20e commit 185a421

File tree

1 file changed

+126
-4
lines changed

1 file changed

+126
-4
lines changed

curriculum/challenges/english/25-front-end-development/review-error-handling/67f39bcb48373420f4f12d62.md

Lines changed: 126 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,135 @@ dashedName: review-error-handling
77

88
# --description--
99

10-
## First topic
10+
## Common Errors in Python
1111

12-
Describe
12+
- **SyntaxError**: The error Python raises when your code does not follow its syntax rules. For example, the code `print("Hello there"` will lead to a syntax error with the message, `SyntaxError: '(' was never closed`, because the code is missing a closing parenthesis.
13+
- **NameError**: Python raises a `NameError` when you try to access a variable or function you have not defined. For instance, if you have the line `print(username)` in your code without having a `username` variable defined first, you will get a name error with the message `NameError: name 'username' is not defined`.
14+
- **TypeError**: This is the error Python throws when you perform an operation on two or more incompatible data types. For example, if you try to add a string to a number, you'll get the error `TypeError: can only concatenate str (not "int") to str`.
15+
- **IndexError**: You'll get an `IndexError` if you access an index that does not exist in a list or other sequences like tuple and string. For example, in a `Hello world` string, the index of the last character is `11`. If you go ahead and access a character this way, `greet = "hello world"; print(greet[12])`, you'll get an error with the message `IndexError: string index out of range`.
16+
- **AttributeError**: Python raises this error when you try to use a method or property that does not exist in an object of that type. For example, calling `.append()` on a string like `"hello".append("!")` will lead to an error with the message `AttributeError: 'str' object has no attribute 'append'`.
1317

14-
## Second topic
18+
## Good Debugging Techniques in Python
1519

16-
Describe
20+
- **Using the `print` function**: Inserting `print()` statements around various points in your code while debugging helps you see the values of variables and how your code flows.
21+
- **Using Python's Built-in Debugger (`pdb`)**: Python provides a `pdb` module for debugging. It's a part of the Python's standard library, so it's always available to use. With `pdb`, you can set a trace with the `set_trace()` method so you can start stepping through the code and inspect variables in an interactive way.
22+
- **Leveraging IDE Debugging Tools**: Many integrated development environments (IDEs) and code editors like Pycharm and VS Code offer debugging tools with breakpoints, step execution, variable inspection, and other debugging features.
23+
24+
## Exception Handling
25+
26+
- **`try...except`**: This is used to execute a block of code that might raise an exception. The `try` block is where you anticipate an error might occur, while the `except` block takes a specified exception and runs if that specified error is raised. Here's an example:
27+
28+
```py
29+
try:
30+
print(22 / 0)
31+
except ZeroDivisionError:
32+
print('You can\'t divide by zero!')
33+
# You can't divide by zero!
34+
```
35+
36+
You can also chain multiple `except` blocks so you can handle more types of exceptions:
37+
38+
```py
39+
try:
40+
number = int(input('Enter a number: '))
41+
print(22 / number)
42+
except ZeroDivisionError:
43+
print('You cannot divide by zero!')
44+
# You cannot divide by zero! prints when you enter 0
45+
except ValueError:
46+
print('Please enter a valid number!')
47+
# Please enter a valid number! prints when you enter a string
48+
```
49+
50+
- **`else` and `finally`**: These blocks extend `try...except`. If no exception occurs, the `else` block runs. The `finally` block always runs regardless of errors.
51+
52+
```py
53+
try:
54+
result = 100 / 4
55+
except ZeroDivisionError:
56+
print('You cannot divide by zero!') # This will not run
57+
else:
58+
print(f'Result is {result}') # Result is 25.0
59+
finally:
60+
print('Execution complete!') # Execution complete!
61+
```
62+
63+
- **Exception Object**: This lets you access the exception itself for better debugging and printing the direct error message. To access the exception object, you need to use the `as` keyword. Here's an example:
64+
65+
```py
66+
try:
67+
value = int('This will raise an error')
68+
except ValueError as e:
69+
print(f'Caught an error: {e}')
70+
# Caught an error: invalid literal for int() with base 10: 'This will raise an error'
71+
```
72+
73+
- **The `raise` Statement**: This allows you to manually raise an exception. You can use it to throw an exception when a certain condition is met. Here's an example:
74+
75+
```py
76+
def divide(a, b):
77+
if b == 0:
78+
raise ZeroDivisionError('You cannot divide by zero')
79+
return a / b
80+
```
81+
82+
## Exception Signaling
83+
84+
The `raise` statement is also useful when you create your own custom exceptions, as you can use it to throw an exception with a custom message. Here's an example of that:
85+
86+
```py
87+
class InvalidCredentialsError(Exception):
88+
def __init__(self, message="Invalid username or password"):
89+
self.message = message
90+
super().__init__(self.message)
91+
92+
def login(username, password):
93+
stored_username = "admin"
94+
stored_password = "password123"
95+
96+
if username != stored_username or password != stored_password:
97+
raise InvalidCredentialsError()
98+
99+
return f"Welcome, {username}!"
100+
```
101+
102+
Here's a how you can use the `login` function from the `InvalidCredentialsError` exception:
103+
104+
```py
105+
# failed login attempt
106+
try:
107+
message = login("user", "wrongpassword")
108+
print(message)
109+
except InvalidCredentialsError as e:
110+
print(f"Login failed: {e}")
111+
112+
# successful login attempt
113+
try:
114+
message = login("admin", "password123")
115+
print(message)
116+
except InvalidCredentialsError as e:
117+
# This block is not executed because the login was successful
118+
print(f"Login failed: {e}")
119+
else:
120+
# The else block runs if the 'try' block completes without an exception
121+
print(message)
122+
```
123+
124+
The `raise` statement can also be used with the `from` keyword to chain exceptions, showing the relationship between different errors:
125+
126+
```py
127+
def parse_config(filename):
128+
try:
129+
with open(filename, 'r') as file:
130+
data = file.read()
131+
return int(data)
132+
except FileNotFoundError:
133+
raise ValueError('Configuration file is missing') from None
134+
except ValueError as e:
135+
raise ValueError('Invalid configuration format') from e
136+
137+
config = parse_config('config.txt')
138+
```
17139

18140
# --assignment--
19141

0 commit comments

Comments
 (0)