While writing programs, we often encounter situations where the normal flow of program execution needs to be altered due to some conditions. Python provides us with mechanisms to handle such situations via exceptions. Exceptions are events that can modify the flow of control through a program. In Python, you can manually trigger an exception at any point in your program using the raise statement.
Here is a simple example of using the raise statement:
x = -1
if x < 0:
# raise an exception if x is negative
raise Exception('x should not be negative')
In this program, if the value of x is less than 0, an exception of type Exception is raised with the message "x should not be negative". If you were to run this program, it would halt at the raise statement and output the exception message, like this:
Exception: x should not be negative
In addition to Exception, Python comes with several built-in exceptions that you can use to raise more specific types of errors. Here is how you might raise a ValueError:
if n < 0:
# raise a ValueError if n is negative
raise ValueError('Square root not defined for negative numbers')
return n ** 0.5
print(sqrt(4)) # 2.0
print(sqrt(-1)) # ValueError: Square root not defined for negative numbers
In this example, the function sqrt(n) attempts to compute the square root of the number n. However, if n is negative, it raises a ValueError with a specific message.
Note that when you raise an exception, the flow of the program is interrupted. This is often desirable behavior, as it allows you to signal that something unexpected has occurred which the program cannot handle. The specific exception type and message provide more information about the nature of the error.
Challenge: File Reader
In a large software firm, there are multiple code files in a directory. You are asked to write a Python function that opens a file and returns its content. But, it should also be able to handle cases when a file does not exist.
The input to the function is the file name.
The function should read and return the contents of the file. In the case when the file does not exist, it should raise a FileNotFoundError.