Exceptions Errors | SoloLearn: Learn to code for FREE!

0

Exceptions Errors

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

3/5/2020 12:45:44 PM

Mustafa Hayder

3 Answers

New Answer

+3

HonFu Thanks for the clarification

+2

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.

+1

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'.