When should you check for errors using "if", and when should you use exceptions?

When do you use each? I consider that I use, if much more, than exceptions. It looks like I caught the exceptions using my "ifs" before I get them. There is an if in all my code.

+5
source share
4 answers

EAFP: It's easier to ask forgiveness than permission.

The usual Python coding style assumes valid keys or attributes and a catch exception if the assumption is false.

LBYL ( , ), , C.

1

, , , , ! pass, , , !

2

, raise -d, , .

+4

try catch , , , -, , - .., . , , ifs trernary operation.

- , , .

+2

, , , :

- , , , , , .

, , : , , .. :

  • try... finally , , ( , Python),
  • with ( Python),
  • RAII, ( ++).
+2

, , . , if. python try/except . , , , . .

+1

All Articles