|
|||
|
Exceptions in Python:-
1. An exception is an error that occurs while a program is running, causing the program to abruptly halt. 2. You can use the try/except statement to gracefully handle exceptions. 3. An exception is an error that occurs while a program is running. In most cases, an exception causes a program to abruptly halt. 4. The lengthy error message that is shown in the sample run is called a traceback. 5. The traceback gives information regarding the line number(s) that caused the exception. (When an exception occurs, programmers say that an exception was raised.) 6. The last line of the error message shows the name of the exception that was raised brief description of the error that caused the exception to be raised. 7. You can prevent many exceptions from being raised by carefully coding your program. Python, like most modern programming languages, allows you to write code that responds to exceptions when they are raised, and prevents the program from abruptly crashing. Such code is called an exception handler, and is written with the try/except statement. There are several ways to write a try/except statement, but the following general format shows the simplest variation: try: statement statement etc. except ExceptionName: statement statement etc. First the key word try appears, followed by a colon. Next, a code block appears which we will refer to as the try block. The try block is one or more statements that can potentially raise an exception. After the try block, an except clause appears. The except clause begins with the key word except, optionally followed by the name of an exception, and ending with a colon. Beginning on the next line is a block of statements that we will refer to as a handler. When the try/except statement executes, the statements in the try block begin to execute. The following describes what happens next: 1. If a statement in the try block raises an exception that is specified by the ExceptionName in an except clause, then the handler that immediately follows the except clause executes. Then, the program resumes execution with the statement immediately following the try/except statement. If a statement in the try block raises an exception that is not specified by the ExceptionName in an except clause, then the program will halt with a traceback error message. 2. If the statements in the try block execute without raising an exception, then any except clauses and handlers in the statement are skipped and the program resumes execution with the statement immediately following the try /except statement. |