Errors and exceptions

decal·2023년 1월 12일
0

study notes

목록 보기
12/12

SyntaxError

  • when Python is unable to understand code
  • mainly due to typos
  • putting a keyword in the wrong place
  • leaving out symbols (ex. colons, brackets)
  • incomplete statements

IndentationError

  • when there is an incorrect or missing indentation

caret (^)

  • indicates in the console where the error has been found in the code

Python will raise something called an exception when it cannot perform an operation.

When an exception is raised, traceback is shown in the console.
The traceback is best read from bottom to top, to understand what went wrong with our code.

ZeroDivisionError, NameError and TypeError are examples of different types of exceptions.


Sometimes we want to raise an exception when a condition we have defined is not met.

slices = 18
diners = 0

if diners < 1:
  raise Exception("There must be at least one diner")
  
else:
  slices_each = slices / diners

Output:

Traceback (most recent call last): File "file.py", line 5, in <module> raise Exception("There must be at least one diner") Exception: There must be at least one diner

We can define both the kind of error, and the error message, like here with ValueError:

age = -3
if not age >= 0:
  raise ValueError('age cannot be negative')

Output:

Traceback (most recent call last): File "file.py", line 3, in <module> raise ValueError('age cannot be negative') ValueError: age cannot be negative

We can use conditions to validate inputs, and raise an exception when the conditions are not met.

Types of errors:

TypeError
ValueError
KeyError
IndexError
LookupError
(and maybe more)


We often don't want a program to terminate when an exception is encountered. A try and except block can be used for exception handling.

try:
	login(user)
except:
	print("User not known, please try again")

Output:

User not known, please try again

A try and except tend to be used where we know there is a chance of the operation not being possible.

hours = []

try:
  average = sum(hours) / len(hours)
except:
  average = 0

print(average)

Output:

0

We can use pass if we want nothing to be executed after except:

try: 
  print("Hello, " + user)
except:
  pass  

We can use an else statement at the end if we want to execute some code only when no error has been raised.

details = {"name": "Helena",
           "occupation": "carpenter",
           "age": 35}

try: 
  age = details["age"]
except:
 raise NameError("No age value in record")
else:
 print(f"Maximum heart rate is {220 - age}")

Output:

Maximum heart rate is 185

We can use a finally statement at the end if we want to execute some related code regardless of whether an error was raised.

entry = 50

try:
 result = entry * 1.5
except:
 raise ValueError("result cannot be calculated")
else:
  print(result)
finally:
  print("Try another value?")

Output:

75.0
Try another value?

0개의 댓글