Exceptions Errors | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Exceptions Errors

Why do we use Exceptions? While we can use if_statement instead of it!

5th Mar 2020, 12:45 PM
ā€ŽMustafa Haider
ā€ŽMustafa Haider - avatar
3 Respostas
+ 3
HonFu Thanks for the clarification
6th Mar 2020, 11:25 AM
ā€ŽMustafa Haider
ā€ŽMustafa Haider - avatar
+ 3
Mustafa Hayder, in larger programs, where several people work at one software, or when you write some sort of library other people are going to use, you use exceptions to handle wrong usage of the functions you provide. (This is basically the same principle: You deal with something you can't control, like how other people will try to use your functions.) Simple example: def f(n): if not isinstance(n, int): raise TypeError( 'This function needs an int!' ) If this function is called with for example a str, an error will happen, and the user of the function gets a message of what went wrong. And they can use try and except to catch this error and provide a solution procedure.
6th Mar 2020, 11:36 AM
HonFu
HonFu - avatar
+ 2
You use exceptions in cases where you can't control what happens. If you have a menu from which the user has to choose, typing a number from 1 to 5, you won't need it. On the other hand, if you want to read a file, all sorts of things can go wrong: File not there, file corrupted wrong file or whatever. In order to not having your program crash, you specify a solution if 'weird stuff happens'.
5th Mar 2020, 1:53 PM
HonFu
HonFu - avatar