0% found this document useful (0 votes)
12 views12 pages

Python Exception Handling Basics

The document provides an overview of Python Exception Handling, explaining how it allows developers to manage errors gracefully without crashing the program. It covers various aspects such as the difference between exceptions and errors, syntax for handling exceptions using try, except, else, and finally blocks, and the advantages and disadvantages of exception handling. Additionally, it includes examples of catching specific exceptions, raising exceptions, and a practical implementation of a Tkinter application for database connectivity using MySQL.

Uploaded by

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

Python Exception Handling Basics

The document provides an overview of Python Exception Handling, explaining how it allows developers to manage errors gracefully without crashing the program. It covers various aspects such as the difference between exceptions and errors, syntax for handling exceptions using try, except, else, and finally blocks, and the advantages and disadvantages of exception handling. Additionally, it includes examples of catching specific exceptions, raising exceptions, and a practical implementation of a Tkinter application for database connectivity using MySQL.

Uploaded by

vishnuaravindhr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Exception Handling

Python Exception Handling handles errors that occur during the execution of a program. Exception
handling allows to respond to the error, instead of crashing the running program. It enables you to
catch and manage errors, making your code more robust and user-friendly. Let's look at an example:
Handling a Simple Exception in Python
Exception handling helps in preventing crashes due to errors. Here’s a basic example demonstrating
how to catch an exception and handle it gracefully:

# Simple Exception Handling Example


n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError:
print("Can't be divided by zero!")

Output
Can't be divided by zero!
Difference Between Exception and Error
 Error: Errors are serious issues that a program should not try to handle. They are usually
problems in the code's logic or configuration and need to be fixed by the programmer.
Examples include syntax errors and memory errors.
 Exception: Exceptions are less severe than errors and can be handled by the program. They
occur due to situations like invalid input, missing files or network issues.

# Syntax Error (Error)


print("Hello world" # Missing closing parenthesis

# ZeroDivisionError (Exception)
n = 10
res = n / 0
Syntax and Usage
Exception handling in Python is done using the try, except, else and finally blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs

try, except, else and finally Blocks


 try Block: try block lets us test a block of code for errors. Python will "try" to execute the
code in this block. If an exception occurs, execution will immediately jump to the except
block.
 except Block: except block enables us to handle the error or exception. If the code inside the
try block throws an error, Python jumps to the except block and executes it. We can handle
specific exceptions or use a general except to catch all exceptions.
 else Block: else block is optional and if included, must follow all except blocks. The else block
runs only if no exceptions are raised in the try block. This is useful for code that should
execute if the try block succeeds.
 finally Block: finally block always runs, regardless of whether an exception occurred or not.
It is typically used for cleanup operations (closing files, releasing resources).

try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")

Python Catching Exceptions


When working with exceptions in Python, we can handle errors more efficiently by specifying the
types of exceptions we expect. This can make code both safer and easier to debug.
Catching Specific Exceptions
Catching specific exceptions makes code to respond to different exception types differently.
try:
x = int("str") # This will cause ValueError

#inverse
inv = 1 / x

except ValueError:
print("Not Valid!")

except ZeroDivisionError:
print("Zero has no inverse!")

Catching Multiple Exceptions


We can catch multiple exceptions in a single block if we need to handle them in the same way or we
can separate them if different types of exceptions require different handling.
Example:
a = ["10", "twenty", 30] # Mixed list of integers and strings
try:
total = int(a[0]) + int(a[1]) # 'twenty' cannot be converted to int

except (ValueError, TypeError) as e:


print("Error", e)

except IndexError:
print("Index out of range.")
Output
Error invalid literal for int() with base 10: 'twenty'
Catch-All Handlers and Their Risks
Here's a simple calculation that may fail due to various reasons.
try:
# Simulate risky calculation: incorrect type operation
res = "100" / 20

except ArithmeticError:
print("Arithmetic problem.")

except:
print("Something went wrong!")

Output
Something went wrong!

Raise an Exception
We raise an exception in Python using the raise keyword followed by an instance of the exception
class that we want to trigger. We can choose from built-in exceptions or define our own custom
exceptions by inheriting from Python's built-in Exception class.
Basic Syntax:
raise ExceptionType("Error message")
def set(age):
if age < 0:
raise ValueError("Age cannot be negative.")
print(f"Age set to {age}")
try:
set(-5)
except ValueError as e:
print(e)

Output
Age cannot be negative.

Advantages of Exception Handling:


 Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.
 Simplified error handling: Exception handling allows you to separate error handling code
from the main program logic, making it easier to read and maintain your code.
 Cleaner code: With exception handling, you can avoid using complex conditional statements
to check for errors, leading to cleaner and more readable code.
 Easier debugging: When an exception is raised, the Python interpreter prints a traceback
that shows the exact location where the exception occurred, making it easier to debug your
code.
Disadvantages of Exception Handling:
 Performance overhead: Exception handling can be slower than using conditional statements
to check for errors, as the interpreter has to perform additional work to catch and handle
the exception.
 Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex error
handling logic.
 Possible security risks: Improperly handled exceptions can potentially reveal sensitive
information or create security vulnerabilities in your code, so it's important to handle
exceptions carefully and avoid exposing too much information about your program.

Python Built-in Exceptions

Python Built-in Exceptions


Here’s a table listing all the major Python built-in exceptions along with a
brief :

Exception Name Description

BaseException The base class for all built-in exceptions.

Exception The base class for all non-exit exceptions.

Base class for all errors related to arithmetic


ArithmeticError operations.
Exception Name Description

Raised when a division or modulo operation is


ZeroDivisionError performed with zero as the divisor.

Raised when a numerical operation exceeds the


OverflowError maximum limit of a data type.

FloatingPointError Raised when a floating-point operation fails.

AssertionError Raised when an assert statement fails.

Raised when an attribute reference or assignment


AttributeError fails.

IndexError Raised when a sequence subscript is out of range.

KeyError Raised when a dictionary key is not found.

MemoryError Raised when an operation runs out of memory.

NameError Raised when a local or global name is not found.

Raised when a system-related operation (like file I/O)


OSError fails.

Raised when an operation or function is applied to an


TypeError object of inappropriate type.

Raised when a function receives an argument of the


ValueError right type but inappropriate value.

ImportError Raised when an import statement has issues.

ModuleNotFoundError Raised when a module cannot be found.

Raised when an I/O operation (like reading or writing


IOError to a file) fails.
Exception Name Description

Raised when a file or directory is requested but


FileNotFoundError cannot be found.

Raised when the next() function is called and there


StopIteration are no more items in an iterator.

Raised when the user presses Ctrl+C or interrupts


KeyboardInterrupt the program’s execution.

Raised when the [Link]() function is called to exit


SystemExit the program.

Raised when an abstract method that needs to be


NotImplementedError implemented is called.

RuntimeError Raised when a general error occurs in the program.

Raised when the maximum recursion depth is


RecursionError exceeded.

Raised when there is an error in the syntax of the


SyntaxError code.

IndentationError Raised when there is an indentation error in the code.

Raised when the indentation consists of inconsistent


TabError use of tabs and spaces.

Raised when a Unicode-related encoding or decoding


UnicodeError error occurs.

1. BaseException

try:
raise BaseException("This is a BaseException")
except BaseException as e:
print(e)

Output
This is a BaseException
Explanation: This code manually raises a BaseException and catches it, printing the exception
message.
2. Exception
try:
raise Exception("This is a generic exception")
except Exception as e:
print(e)

Output
This is a generic exception

3. ArithmeticError

try:
raise ArithmeticError("Arithmetic error occurred")
except ArithmeticError as e:
print(e)

4 ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError as e:
print(e)
Data base connectivity using SQL

import tkinter as tk
from tkinter import messagebox
import [Link]

# Function to connect to database


def get_connection():
return [Link](
host="localhost",
user="root", # change if needed
password="123qwe", # add your password if set
database="test" # make sure database exists
)

# Insert data
def insert_data():
name = entry_name.get()
age = entry_age.get()
if name == "" or age == "":
[Link]("Error", "All fields are required!")
return
try:
conn = get_connection()
cursor = [Link]()
[Link]("INSERT INTO students (name, age) VALUES (%s, %s)",
(name, age))
[Link]()
[Link]()
[Link]("Success", "Data inserted successfully!")
except Exception as e:
[Link]("Database Error", str(e))

# Fetch data
def fetch_data():
try:
conn = get_connection()
cursor = [Link]()
[Link]("SELECT * FROM students")
rows = [Link]()
[Link]()
result = "\n".join([f"ID:{row[0]} | Name:{row[1]} | Age:{row[2]}" for row
in rows])
[Link]("Student Records", result if result else "No data
found.")
except Exception as e:
[Link]("Database Error", str(e))

# Update data
def update_data():
sid = entry_id.get()
name = entry_name.get()
age = entry_age.get()
if sid == "" or name == "" or age == "":
[Link]("Error", "All fields (ID, Name, Age) are required
for update!")
return
try:
conn = get_connection()
cursor = [Link]()
[Link]("UPDATE students SET name=%s, age=%s WHERE
id=%s", (name, age, sid))
[Link]()
[Link]()
if [Link] == 0:
[Link]("Not Found", f"No record with ID {sid}")
else:
[Link]("Success", "Record updated successfully!")
except Exception as e:
[Link]("Database Error", str(e))

# Delete data
def delete_data():
sid = entry_id.get()
if sid == "":
[Link]("Error", "ID is required to delete a record!")
return
try:
conn = get_connection()
cursor = [Link]()
[Link]("DELETE FROM students WHERE id=%s", (sid,))
[Link]()
[Link]()
if [Link] == 0:
[Link]("Not Found", f"No record with ID {sid}")
else:
[Link]("Success", "Record deleted successfully!")
except Exception as e:
[Link]("Database Error", str(e))

# Tkinter window
root = [Link]()
[Link]("Tkinter + MySQL CRUD Example")
[Link]("1200x600")
[Link](root,text ="STUDENT INFORMATION
SYSTEM",bg="yellow",font=("ARIEL",40)).pack(pady=5)
# Labels & Entries
[Link](root, text="ID (for Update/Delete):").pack(pady=5)
entry_id = [Link](root)
entry_id.pack(pady=5)

[Link](root, text="Name:").pack(pady=5)
entry_name = [Link](root,bg="red",fg="blue")
entry_name.pack(pady=5)

[Link](root, text="Age:").pack(pady=5)
entry_age = [Link](root)
entry_age.pack(pady=5)

# Buttons
[Link](root, text="Insert Data", width=20,
command=insert_data).pack(pady=5)
[Link](root, text="Fetch Data", width=20,
command=fetch_data).pack(pady=5)
[Link](root, text="Update Data", width=20,
command=update_data).pack(pady=5)
[Link](root, text="Delete Data", width=20,
command=delete_data).pack(pady=5)
[Link]()

You might also like