Exception Handling
Exception handling:
We don't want to scare the user away
We don't want the user to see log like stack traces when errors are shown
That's where exception handling comes in
Raw code before exception handling:
Will generate a type error as the
input
function converts anything you give it to stringAny code other than 0 generates an error
Error:
By handling exceptions, you don't display the above stack to the user
Code after exception handling:
To handle the errors there is a special syntax called
try
andexcept
By handling the Exception, the rest of the code in the grand scope will run
Such as
print('HELLO')
This is due to scope
The exception will be handled gracefully and will not crash the rest of the program
Exception handling should be used only if you don't have any control over how it is used
Example:
The software goes to the internet and downloads files, and the user runs your program with no internet access, that could cause a crash
Another example is if the program relies on a file to be on the file system. If that is not there it will crash
The above code does not need any exception handling really, as the data type is in our control
isinstance
checks for data types specified
Last updated