[go: up one dir, main page]

0% found this document useful (0 votes)
6 views4 pages

exception handlin

Exception handlin

Uploaded by

gdeep19136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

exception handlin

Exception handlin

Uploaded by

gdeep19136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

The terms "runtime errors" and "exceptions" are related but have distinct meanings in programming:

### 1. Runtime Errors


- Definition : Runtime errors are errors that occur during the execution of a program (i.e., at runtime), rather
than at the time of code compilation or parsing.
- Characteristics :
- They interrupt the normal flow of a program and often lead to unexpected behaviour or program crashes.
- They include both exceptions (which are specific, predefined error types in Python) and other
unpredictable issues that can halt the program.
- Runtime errors could be caused by various reasons, such as insufficient memory, incorrect logic, or
unavailable resources (like files or network connections).
- Examples : Division by zero, accessing a null reference in some languages, or trying to use a file that isn’t
available.

### 2. Exceptions
- Definition : Exceptions are specific types of runtime errors that are "raised" by Python when it encounters
an unexpected condition.
- Characteristics :
- They are a subset of runtime errors in Python, specifically designed to be caught and managed through
exception handling (`try`, `except`).
- When an exception occurs, Python raises an error object, which can then be handled using `except`
blocks.
- If an exception is not handled, it will terminate the program and show an error traceback.
- Examples :
- ZeroDivisionError : Raised when trying to divide by zero.
- ValueError : Raised when a function receives an argument of the correct type but an invalid value.
- FileNotFoundError : Raised when attempting to open a file that doesn’t exist.

exceptions are a subset of runtime errors in Python that can be managed using `try-except` blocks, allowing
programs to handle errors gracefully.
Not all runtime errors are exceptions, but all exceptions are runtime errors.

### Exception Handling in Python

Exception handling allows a program to manage errors gracefully, helping avoid unexpected crashes. Python
uses the try, except, else, and finally blocks to handle exceptions.

### Common Exceptions with Examples

1. ZeroDivisionError

This occurs when a number is divided by zero.

Example:

result = 10 / 0
print("Error: You cannot divide by zero.")

2. TypeError

This exception is raised when an operation is applied to an object of an inappropriate type.


Example:

result = "hello" + 5
print(result)

Output:

Error: You cannot add a string and an integer.

3. ValueError

Occurs when a function receives an argument of the correct type but an invalid value.
Example:

number = int("hello")
print(number)

Output:

Error: Invalid literal for int().

4. FileNotFoundError

Raised when a file or directory is requested but cannot be found.

Example:

with open("nonexistent_file.txt", "r") as file:


content = file.read()
print(content)

Output:

Error: File not found.

5. IndexError

Occurs when trying to access an invalid index of a list or another sequence.

Example:

my_list = [1, 2, 3]
element = my_list[5]
print(element)

Output:

Error: List index out of range.

The try-except Block


The try-except block helps you handle exceptions and define actions for specific errors.

Syntax:

python
try:
# Code that might raise an exception
except ExceptionType:
# Code that runs if the specified exception occurs

Example:

python
try:
num = int(input("Enter a number: "))
print("Result:", 10 / num)
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Please enter a valid integer.")

Output Examples:

If user enters 0:

Enter a number: 0
Error: You cannot divide by zero.

If user enters hello:

Enter a number: hello


Error: Please enter a valid integer.

Using try-except-else

The else block runs only if no exception occurs in the try block.

Syntax:

try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code that runs if no exception occurs

Example:
python
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
else:
print("Result:", result)

Output Examples:

If user enters 2:

Enter a number: 2
Result: 5.0

If user enters 0:

Enter a number: 0
Error: You cannot divide by zero.

The finally Block

The finally block is used to execute code regardless of whether an exception occurs or not. This is helpful
for cleanup tasks like closing files or releasing resources.

Syntax:

python
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
finally:
# Code that runs regardless of exceptions

Example:

python
j

Summary of Block Flow

1. try: Code that might cause an exception.


2. except: Code to handle specific exceptions.
3. else: (Optional) Runs if no exception occurs.
4. finally: (Optional) Always runs, regardless of exceptions.

Using try, except, else, and finally blocks provides a way to make programs robust and prevent unexpected
crashes.

You might also like