Python code doesn’t work always as we want and therefore raises errors and exceptions. Errors are more common to happen due to syntax like missing parenthesis or indentation. Exceptions happen when something really goes wrong with the execution of the code, like iterating over a list and going out-of-bounds of the list size or trying to access a not existing file.
It is possible to write programs that handle specific exceptions letting the user control how the program will respond to an exception; note that a user-generated interruption is signaled by raising the KeyboardInterrupt exception.
Output:
Please enter a number: 2
The example above tries to ask for an input that is a number and keeps on trying in a while loop until it works out well. If the user inputs anything other than a number an exception will be raised “catching” it. This is a way to avoid the program to crash telling it “Okay, try to do this but lookout that it might happen this (whatever exception is being caught in the except field), and if it happens then do this (which in this case is printing a message)”.
• try clause (whatever is between the try and the first except) is executed.
• If no exception occurs, the except clause is skipped and execution of the try statement is finished.
• If an exception occurs during the execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
• If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a default message.
Programs may name their own exceptions by creating a new exception class.
Exceptions should typically be derived from the Exception class. Exception classes can be defined which do anything any other class can do, but are usually kept simple.
For a list of all built-in exceptions that Python supports by default, refer the link: https://docs.python.org/3/library/exceptions.html