-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocument4.rtf
More file actions
105 lines (105 loc) · 6.32 KB
/
Copy pathDocument4.rtf
File metadata and controls
105 lines (105 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}}
{\*\generator Riched20 10.0.10586}\viewkind4\uc1
\pard\sa200\sl276\slmult1\f0\fs22\lang9 Error Handling Review\par
Common Errors in Python\par
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.\par
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.\par
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.\par
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.\par
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'.\par
Good Debugging Techniques in Python\par
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.\par
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() function so you can start stepping through the code and inspect variables in an interactive way.\par
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.\par
Exception Handling\par
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:\par
\par
try:\par
print(22 / 0)\par
except ZeroDivisionError:\par
print('You can\\'t divide by zero!')\par
# You can't divide by zero!\par
You can also chain multiple except blocks so you can handle more types of exceptions:\par
\par
try:\par
number = int(input('Enter a number: '))\par
print(22 / number)\par
except ZeroDivisionError:\par
print('You cannot divide by zero!')\par
# You cannot divide by zero! prints when you enter 0\par
except ValueError:\par
print('Please enter a valid number!')\par
# Please enter a valid number! prints when you enter a string \par
else and finally: These blocks extend try...except. If no exception occurs, the else block runs. The finally block always runs regardless of errors.\par
\par
try:\par
result = 100 / 4\par
except ZeroDivisionError:\par
print('You cannot divide by zero!') # This will not run\par
else:\par
print(f'Result is \{result\}') # Result is 25.0\par
finally:\par
print('Execution complete!') # Execution complete!\par
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:\par
\par
try:\par
value = int('This will raise an error')\par
except ValueError as e:\par
print(f'Caught an error: \{e\}')\par
# Caught an error: invalid literal for int() with base 10: 'This will raise an error'\par
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:\par
\par
def divide(a, b):\par
if b == 0:\par
raise ZeroDivisionError('You cannot divide by zero')\par
return a / b\par
Exception Signaling\par
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:\par
\par
class InvalidCredentialsError(Exception):\par
def __init__(self, message="Invalid username or password"):\par
self.message = message\par
super().__init__(self.message)\par
\par
def login(username, password):\par
stored_username = "admin"\par
stored_password = "password123"\par
\par
if username != stored_username or password != stored_password:\par
raise InvalidCredentialsError()\par
\par
return f"Welcome, \{username\}!"\par
Here's a how you can use the login function with the InvalidCredentialsError exception:\par
\par
# failed login attempt\par
try:\par
message = login("user", "wrongpassword")\par
except InvalidCredentialsError as e:\par
print(f"Login failed: \{e\}")\par
else:\par
print(message)\par
\par
# successful login attempt\par
try:\par
message = login("admin", "password123")\par
except InvalidCredentialsError as e:\par
# This block is not executed because the login was successful\par
print(f"Login failed: \{e\}")\par
else:\par
# The else block runs if the 'try' block completes without an exception\par
print(message)\par
The raise statement can also be used with the from keyword to chain exceptions, showing the relationship between different errors:\par
\par
def parse_config(filename):\par
try:\par
with open(filename, 'r') as file:\par
data = file.read()\par
return int(data)\par
except FileNotFoundError:\par
raise ValueError('Configuration file is missing') from None\par
except ValueError as e:\par
raise ValueError('Invalid configuration format') from e\par
\par
config = parse_config('config.txt')\par
}