7. Name a few general built-in exceptions that Python possesses.
Several built-in Python exceptions are frequently encountered when handling errors. Some of the important exceptions are:
TypeError: Raised when an operation or function is applied to an object of inappropriate type.
Example:
len(5) This raises a TypeError because len() cannot be applied on an integer.
ValueError: Raised when a function is applied to an argument of the right type but an inappropriate value.
Example:
int("hello") will raise ValueError because "hello" as a string does not have a proper conversion to an int.
IndexError: Raised when trying to access an element of a list( sequence) using out of bounds index.
Example:
my_list = [1, 2, 3]
print(my_list[5]) would raise IndexError.
KeyError: Raised when attempting to access a key in the dictionary that does not exist.
Example:
my_dict = {"a": 1};
print(my_dict["b"]) would raise KeyError.
FileNotFoundError: Raised when trying to open a file that does not exist.
Example:
open("nonexistent_file.txt") will raise FileNotFoundError.
ZeroDivisionError: Raised when a divide by zero operation would be encountered.
Example:
10/0 would raise a ZeroDivisionError.
These are only a few examples many more built-in exceptions in Python can be used to deal with various types of errors in your program.
8. How do you handle a certain type of exception?
To catch errors of a certain kind in Python one makes use of a construct called try and except. In this case, the try is for the code that might fail and it jumps to the corresponding except part if any error has occurred in that portion.
You can output the specific type of errors in the except block which in turn allows a broader classification of how you will respond based on the specific error that has occurred.
Example:
try:
# This might raise a ValueError
number = int(input("Enter a number: "))
# This might raise a ZeroDivisionError
result = 10 / number
except ValueError:
print("You didn't enter a number. Please type a valid number.")
except ZeroDivisionError:
print("You can't divide by zero. Please enter a number other than zero.")
What's happening here?
If the user types something that isn't a number (like a word), Python will raise a ValueError. The program catches that error and tells the user to enter a valid number.
If the user types 0, dividing by zero would raise a ZeroDivisionError. The program then prints a helpful message and avoids crashing.
This error handling makes your application quite user-friendly because in case of wrong input, the application would not crash instead it would sweetly show an error and give a chance to the user to rectify and try again.
9. Do you have multiple except clause? Why?
Frankly, one can use multiple except blocks in Python for a very good reason. Much would go wrong with codes as they run. Handling each type of error in different except blocks would give clearer messages to aid in fixing.
Every except block is written for a certain type of error. For instance, one might be for input errors, while others could be for divisions by zero, thus making the code more readable and allowing a better understanding among users about what wrong it just did.
Consider this example:
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("You can't divide by zero.")
except Exception as e:
print("Something else went wrong:", e)
The advantage of some individual except blocks is that you can catch and handle all the exceptions rightly. With them, code can only get more useful and reduce chances of confounding error messages or missing out on errors raised.
10. What is the base for every exception?
BaseException is the most basic class to which all kinds of python exceptions belong.
All built-in exceptions and user-defined exceptions in Python derive instantly or otherwise from this BaseException class. For all practical purposes, BaseException is not used directly but indirectly through its subclass Exception, which is the main class for normal errors.
This means when you are writing your own exceptions or using try and except to handle exceptions, you are actually dealing with the exception class that for all practical purposes is derived from BaseException.
For example:
try:
raise Exception("This is an error")
except Exception as e:
print("Caught an exception:", e)
In this example, Exception is simply a subclass of BaseException.
In summary:
BaseException is at the root for all exceptions.
The common base class for all these exceptions is Exception, which is just the base class for most errors in programs.
11. How do you raise an exception manually?
You can throw or raise an exception in Python after which it stops execution. This can be done exactly by using "raise" when certain unexpected wrong events occur. It would really help if you want to see some particular condition in your codeactive and it can interact with the end user or the developer to show there is something wrong.
Example:
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Here, we check if the age is less than zero and if so, we raise a ValueError with a clear message. Since there is no sense in stating that a person has a negative age, this will catch mistakes early, making the program more reliable.
You can raise various forms of errors - TypeError, ValueError or even your own custom error types. This way, you are able to better control how the program handles different situations that "go wrong".
12. Why should you consider raising an exception?
Exception raising in Python is one of the widely practiced techniques to design solid maintainable software. Raise an exception rather than returning an ambiguous value whenever a function confronts an error or a condition that it cannot find a resolution for.
This clear signaling of an error, as opposed to rendering a value in a function that must be left undetected, is essential to prevent silent failures and ensure that things are handled by the public code according to their extenuated case.
Raising the exception constitutes a contract where, if anything goes wrong, it has to be handled within a try...except block by the caller.
It shapes a more disciplined way of handling errors, where the end products are less prone and crash-free applications and easy debugging. Obviously, well-defined exceptions, especially custom ones, are regarded to carry with them useful context regarding the nature of the exception, which in turn fast-tracks the process of diagnosis and resolution.
With much clearer explicit signaling, raising exceptions adds much more structural and clarity value to your codebase. It separates out cleanly the error handling mechanisms from the core logic of a function. The primary path of execution is focused on what you want done while excluding exceptional situations from those activities, each handled in their except blocks.
It becomes very easy to read and maintain the code as it distinguishes between normal operations and error recovery by just looking at the flow. Also, exceptions naturally propagate up through the call stack until an appropriate handler can be found.
This thus allows the entire error handling to be centralized at the level where the application has sufficient context to decide on the most appropriate course of action be it logging the error, retrying the operation or informing the user gracefully. This is the hallmark of professional error management in developing software.
13. What is the aims for the else clause in try except else?
The else statement in a try/except/else construct will run in Python only if no exception has been raised in the try statement.
Here's the purpose:
The else clause lets you separate the code that should run only when everything goes right meaning no error occurred from the code that handles errors.
Why use it?
Using else ensures that your code is clean and easy to read. You can put the main logic in the else clause and keep the exception handling logic in the except clause. This way it becomes very evident what takes place when things go right versus when something goes wrong.
Example:
try:
number = int(input("Enter a number: "))
except ValueError:
print("That's not a valid number.")
else:
print("You entered:", number)
This means:
If the input is not a number, then the except block runs.
If the input is valid, then the else block runs.
Thus, the intention of the else clause is to separate successful code from error handling code in order to render your program neater and easier to read.
14. What are the best practices of exception handling?
Some of the best practices of exception handling in Python explained in a clear and easy language are given below.
1. Target Exceptions Specifically
Under normal circumstances, never use general except: or except Exception:. Like almost all of us do, catch specific exceptions like ValueError, KeyError or ZeroDivisionError so you are only dealing with that specific error that you intended to catch.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
2. Don’t Suppress Exceptions Silently
Don't leave the code in the except statement empty. This means that the debugger will find it hard to hunt down the source of the error. Always log or print something helpful.
# Not good
try:
risky_function()
except:
pass # silently ignores all errors Bad idea
# Better
except Exception as e:
print("An error occurred:", e)
3. Cleanup in Finally
The finally block is used when you want to close files, release resources, and do any cleanup, irrespective of whether an error occurred or not.
try:
file = open('data.txt')
# process file
except FileNotFoundError:
print("File not found.")
finally:
file.close()
4. Keep Try Blocks Short
Place only the code which could throw exceptions inside the try block. Keep the rest of the code outside of it so that you do not end up handling unintended exceptions.
# Better structure:
try:
number = int(input("Enter a number: "))
except ValueError:
print("That's not a number.")
5. Never Use Exceptions to Control Flow
Do not use exceptions to mold the working of your program. They were devised for dealing with errors that are unexpected, not for replacing your if-else logic.
# Bad:
try:
value = my_dict['key']
except KeyError:
value = 'default' # Better to use get(): my_dict.get('key', 'default')
6. Log Exceptions
In larger programs, use the logging module in Python to log the exception instead of printing it out.
import logging
try:
risky_code()
except Exception as e:
logging.error("Something went wrong: %s", e)
7. Raise Exceptions with Meaningful Messages
If possible, when raising the errors by yourself, put some information in the error messages. This will aid the user or developer in understanding what went wrong.
raise ValueError("Age must be a positive number.")
When you stick to these guidelines, you create a code that is simple to understand, is reliable, and can be fixed with relative ease if something goes wrong.
15. How can you get an exception on error message?
The error message can also be get using the try-except block in Python, where in exceptions are captured using the as try-except clause. That allows one to store the exception in some variable and print out the error message.
Example:
try:
number = int("abc")
except ValueError as error:
print("An error occurred:", error)
Output:
An error occurred: invalid literal for int() with base 10: 'abc'
Discussion
ValueError is the expected type of error.
"as error" saves the actual error into the variable named error.
"print(error)" displays the message that explains what went wrong.
This helps debugging and creates nice error messages to show users.
16. When would you want to create a custom exception?
In Python programming, at times the need arises to define new exception classes when the available built-in exceptions do not sufficiently capture a particular error that could be thrown by the code. By allowing a more meaningful way of handling errors especially when the logic in code becomes complex these exceptions come into their own more so in the case of larger applications.
For instance, within a banking application, trying to withdraw an amount higher than the amount available in the account will lose the specificity of the problem in just raising a ValueError. Having an exception defined as InsufficientFundsError would unambiguously communicate the issue, thus aiding debugging and clarifying the program flow.
Custom exceptions work much like common exceptions, say for illustration:
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("You cannot withdraw more than your current balance.")
return balance - amount
try:
withdraw(500, 600)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")
Custom exceptions such as InsufficientFundsError will ensure lesser ambiguity and more maintainability on the code. Instead of raising a generic error with less context that might confuse someone, the exception specifies what has gone wrong.
17. How do you create a very basic custom exception?
You simply need to create a new class that inherits from the built-in Exception class to create your own very basic custom exception in Python. This makes it possible for you to raise and catch your own form of error just like any other exception.
An example would be as follows:
class MyCustomError(Exception):
pass
# Using the custom exception
def check_number(x):
if x < 0:
raise MyCustomError("Negative numbers are not allowed.")
return x
try:
check_number(-5)
except MyCustomError as e:
print(f"Error: {e}")
In this example:
MyCustomError is the custom user-defined exception.
It is intended to be used in the check_number() function to raise an error when the input value is negative.
The try-except block catches and handles the custom exception with a very precise message.
This very simple structure is useful when you want your code to be more readable while also making errors easier to explain.
18. What is the with statement and how is it related to exceptions?
The with statement ensures that a block of code is executed in which certain tasks are automatically handled, thus preventing oversights such as not closing a file or releasing a resource. Using the with statement ensures that resources are released safely even in error situations, thereby ensuring an extra layer of safety.
For instance, if you have a procedure that opens a file and some exceptions happen while reading that file, using the with statement will, nevertheless, guarantee that the file is closed properly.
Look at this very simple example:
try:
with open('example.txt', 'r') as file:
data = file.read()
print(data)
except FileNotFoundError:
print("The file was not found.")
In this example:
The with statement handles everything to do with opening and closing the file.
If an exception such as a FileNotFoundError occurs, it falls under the control of the except block.
From that point, the argument could be made that, were reading the file to crash the program, statement with would still ensure the file was closed.
Hence, your code becomes neater and safer to use especially when dealing with files, sockets and database connections.
19. How can I use the same block of code to catch two different types of exceptions?
Having a single except block for multiple exceptions is permitted if the exceptions are specified within a tuple. If any of the specified exceptions arise in the try block, that same except block will handle the exception.
An illustration of his conviction can be found in the following:
try:
number = int(input("Enter a number: "))
result = 10 / number
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
What happens here is that:
ValueError occurs when the input is not a number.
ZeroDivisionError occurs if the user enters 0, since "mother" has no definition.
Both exceptions are handled by the except block with the same piece of code.
This keeps your code cleaner when handling different errors in the same way.
20. When you see an unhandled exception in your code, what do you do first?
When an unhandled exception happens in your code, first pay attention to what the error message and traceback present. They tell you a lot regarding where the error happened and what part of the code triggered it.
After you've got that information, you can:
Define the exception type: Is it ValueError, IndexError, TypeError etc.? That will lead you to understand what really went wrong.
Check the faulty piece of code: Look into the line or block erased in the traceback to compare what triggered the exception.
Come up with a solution: Discuss how such an error could be rectified. An example would include when the error occurred due to wrong input, you may want to add input validation or catch such an error using a try-except block gracefully.
Here is an example:
try:
number = int(raw_input("Enter a number: "))
result = 10/number # Could result in ZeroDivisionError
except ZeroDivisionError as e:
print("Error: %s. You cannot divide by zero." % e)
except ValueError as e:
print("Error: Invalid input. Please enter a valid number.")
Here, if the user enters 0 a ZeroDivisionError occurs and a message of "You cannot divide by zero" would display. If a non numeric input is entered a ValueError would raise and display a message saying "Invalid input". Exception handling can prevent crashes and provide meaningful interpretation.
21. Can you have a finally block without an except block? What would be the purpose of such a construct?
Yes, in Python, it is legitimate to use a finally without an except block. The main purpose of the finally block is to provide the statements that should have been executed no matter what happened in the try block: whether an exception occurred or not.
In practice, there are certain situations where the programmer would like to ensure that cleanup is done: closing a file, acquiring a lock, disconnecting from a database, etc., irrespective of whether or not exceptions were being explicitly handled at that point. The finally will run when all blocks such as try get executed, regardless of whether they succeed or fail or whether the exception raised goes uncaught.
Example:
def write_file():
try:
f = open("example.txt", "w")
f.write("Hello, Python!")
finally:
f.close()
print("File closed successfully.")
In this example, even if something goes wrong while writing to the file, the file will still be closed because of the finally block. This helps prevent resource leaks.
In short, you use a finally without an except block to ensure that, even if at this particular point you don't want to catch that exception, some code still has to run for cleanup or logging purposes. This creates more reliable and safer code.
22.How does the finally block interact with exceptions that are not handled by any except block within the same try...except...finally structure?
The finally block of Python will be executed following all blocks of code, even in the presence of an except block with the error. It may be said that in the event of an exception raised inside the try block with no corresponding except block, the finally block will still be executed before the program exits or propagates the error. This guarantees that any cleanup would still be performed, such as closing files or releasing resources.
Example:
try:
print("Trying something risky")
result = 5 / 0 # Raises ZeroDivisionError
finally:
print("Cleanup in finally block")
No matter that exception isn't caught, indeed the message inside finally will be printed before the program shows the error.
Previous Topic==> Python Tuple and Sets FAQ || Next Topics==> Python OOPS Object Oriented FAQ
Other Topic==>
Input In Python
Top SQL Interview Questions
Employee Salary Management SQL FAQ!.
Top 25 PL/SQL Interview Questions
Topics Wise Top SQL Interview Questions