Exception Handling in python programming.pptxshririshsri
Â
Here...this ppt shows the programming language named "python".In python,file 'exception handing' and their examples & exercises are given.it gives the clear idea of the python exception.
Exception handling in Python allows programs to handle errors and exceptions gracefully to prevent crashes. There are various types of exceptions that can occur. The try and except blocks allow code to execute normally or handle exceptions. Finally blocks let code execute regardless of exceptions. Raise statements can be used to explicitly raise exceptions if conditions occur. Assertions validate conditions and raise exceptions if validation fails. Exceptions allow errors to be detected and addressed to improve program reliability.
The document discusses different types of errors in programming:
1. Compile-time errors occur due to syntax errors in the code and prevent the program from compiling. Examples include missing colons or incorrect indentation.
2. Runtime errors occur when the Python virtual machine (PVM) cannot execute the bytecode. Examples include type errors during operations or accessing elements beyond the bounds of a list.
3. Logical errors stem from flaws in the program's logic, like using an incorrect formula.
Exception handling allows programmers to anticipate and handle errors gracefully. The try/except blocks allow specific code to handle exceptions of a given type. Finally blocks ensure code is executed after the try/except blocks complete.
Types of errors include syntax errors, logical errors, and runtime errors. Exceptions are errors that occur during program execution. When an exception occurs, Python generates an exception object that can be handled to avoid crashing the program. Exceptions allow errors to be handled gracefully. The try and except blocks are used to catch and handle exceptions. Python has a hierarchy of built-in exceptions like ZeroDivisionError, NameError, and IOError.
The document discusses Python exception handling. It describes three types of errors in Python: compile time errors (syntax errors), runtime errors (exceptions), and logical errors. It explains how to handle exceptions using try, except, and finally blocks. Common built-in exceptions like ZeroDivisionError and NameError are also covered. The document concludes with user-defined exceptions and logging exceptions.
The document discusses Python exception handling. It defines what exceptions are, how to handle exceptions using try and except blocks, and how to raise user-defined exceptions. Some key points:
- Exceptions are errors that disrupt normal program flow. The try block allows running code that may raise exceptions. Except blocks define how to handle specific exceptions.
- Exceptions can be raised manually using raise. User-defined exceptions can be created by subclassing built-in exceptions.
- Finally blocks contain cleanup code that always runs whether an exception occurred or not.
- Except blocks can target specific exceptions or use a generic except to handle any exception. Exception arguments provide additional error information.
This document discusses exceptions in Python programming. It defines an exception as an event that disrupts normal program flow, such as a runtime error. The document explains how to handle exceptions using try and except blocks. Code is provided to demonstrate catching specific exception types, catching all exceptions, and raising new exceptions. Finally, it notes that exceptions can provide additional error details through arguments.
This document discusses Python errors and exceptions. It explains that there are two types of errors in Python: syntax errors, which occur due to incorrect syntax, and exceptions (also called logical errors), which occur during runtime. It provides examples of common exceptions like ZeroDivisionError, FileNotFoundError, and ImportError. The document also discusses how to handle exceptions using try/except blocks in Python and how to raise custom exceptions. Finally, it covers some advanced exception handling techniques like specifying multiple exceptions, using else and finally blocks, and raising exceptions manually.
This document discusses exception handling in Python. It explains that exceptions occur when runtime errors happen and stop the normal flow of a program. Exceptions can be caused by syntax errors or errors in code that result in an exception even if the syntax is valid, like division by zero. The try and except statement is used to handle exceptions - critical code is placed in the try block and exception handling code is placed in the except block. Multiple except blocks can handle different exceptions. An else block will run only if no exceptions occurred. Finally, a finally block is always executed after try and except to clean up resources. Exceptions can also be manually raised using raise or re-raised after handling.
The document discusses exceptions in Python. It defines exceptions as events that disrupt normal program flow, and explains that Python scripts must either handle exceptions or terminate. It provides examples of different exception types, and describes how to handle exceptions using try and except blocks. Code in the try block may raise exceptions, which are then handled by corresponding except blocks. Finally, an else block can contain code that runs if no exceptions occur.
Python Programming - X. Exception Handling and AssertionsRanel Padon
Â
The document discusses exception handling in Python programming. It defines an exception as an event that occurs during program execution that indicates an error. It describes how Python uses try and except blocks to handle exceptions. The try block contains code that may raise exceptions, and except blocks handle specific exceptions. Finally blocks always execute to cleanup resources, even if no exception occurs. User-defined exceptions should inherit from the built-in Exception class. The raise statement throws exceptions, and assertions act like raise-if statements to validate program logic.
Exceptions in Python represent errors and unexpected events that occur during program execution. There are several ways to handle exceptions in Python code:
1. Try and except blocks allow catching specific exceptions, with except blocks handling the exception.
2. Multiple except blocks can handle different exception types. The else block runs if no exception occurs.
3. Exceptions can be raised manually with raise or instantiated before raising. Finally blocks ensure code runs regardless of exceptions.
Exception Handling in Python allows programs to handle errors and exceptions gracefully. It prevents programs from crashing when errors occur. There are several key aspects of exception handling: exceptions represent errors, try and except blocks catch and handle exceptions, the else block runs if no exception occurs, and finally ensures cleanup code runs regardless of exceptions. User-defined exceptions can also be created to handle custom errors in a program.
Errors in Python programs are either syntax errors or exceptions. Syntax errors occur when the code has invalid syntax and exceptions occur when valid code causes an error at runtime. Exceptions can be handled by using try and except blocks. Users can also define their own exceptions by creating exception classes that inherit from the built-in Exception class. The finally block gets executed whether or not an exception was raised and is used to define clean-up actions. The with statement is also used to ensure objects are cleaned up properly after use.
This document discusses exception handling in Python. It defines errors and exceptions, and describes the different types of errors like syntax errors, semantic errors, type errors, runtime errors, and logical errors. It explains how exceptions occur during program execution. The try and except blocks are described for handling exceptions, with examples given. The raise statement is explained for raising user-defined exceptions. Common built-in exceptions in Python like IOError, ImportError, ValueError and KeyboardInterrupt are also listed.
Understanding Errors and Exceptions in Python
Errors and exceptions are fundamental concepts in Python programming that help developers manage unexpected situations and ensure robust application performance. This guide provides a comprehensive overview of errors and exceptions, their types, and best practices for handling them effectively.
What Are Errors?
Errors are issues that occur during the execution of a program, causing it to stop functioning correctly. They can be broadly categorized into two main types:
Syntax Errors:
These occur when the code violates the rules of the Python language. Syntax errors are detected at compile time, preventing the program from running.
Example:
python
Run
Copy code
print("Hello, World!" # Missing closing parenthesis
Runtime Errors:
These occur during the execution of the program, often due to invalid operations or unexpected conditions. Runtime errors can lead to program crashes if not handled properly.
Example:
python
Run
Copy code
result = 10 / 0 # ZeroDivisionError
What Are Exceptions?
Exceptions are a specific type of runtime error that disrupts the normal flow of a program. They provide a way to signal that an error has occurred and can be caught and handled gracefully. Python has a built-in mechanism for managing exceptions, allowing developers to write more resilient code.
Common Built-in Exceptions
ValueError: Raised when a function receives an argument of the right type but an inappropriate value.
TypeError: Raised when an operation or function is applied to an object of an inappropriate type.
IndexError: Raised when trying to access an index that is out of range in a list or tuple.
KeyError: Raised when a dictionary key is not found.
FileNotFoundError: Raised when trying to access a file that does not exist.
Exception Handling in Python
Python provides a robust mechanism for handling exceptions using try, except, else, and finally blocks:
Try Block: Contains the code that may raise an exception.
Except Block: Catches and handles the exception if it occurs.
Else Block: Executes if the try block does not raise an exception.
Finally Block: Executes regardless of whether an exception occurred, often used for cleanup actions.
Example:
python
Run
Copy code
try:
value = int(input("Enter a number: "))
except ValueError:
print("That's not a valid number!")
else:
print("You entered:", value)
finally:
print("Execution complete.")
Best Practices for Error and Exception Handling
Be Specific: Catch specific exceptions rather than using a generic except clause to avoid masking other issues.
Log Errors: Implement logging to capture error details for debugging and analysis.
Use Custom Exceptions: Define custom exception classes for more meaningful error handling in complex applications.
Graceful Degradation: Ensure that your application can continue to function or provide useful feedback even when errors occur.
đđąđCOPY LINK & PASTE ON GOOGLE https://dr-kain-geera.info/đđ
Wondershare UniConverter is a versatile multimedia tool that combines video conversion, editing, downloading, burning, and transfer capabilities. It's designed to streamline video production by supporting over 1,000 media formats and offering features like video enhancement, basic editing, and batch processing. Essentially, it's a comprehensive video toolbox for various tasks.
Types of errors include syntax errors, logical errors, and runtime errors. Exceptions are errors that occur during program execution. When an exception occurs, Python generates an exception object that can be handled to avoid crashing the program. Exceptions allow errors to be handled gracefully. The try and except blocks are used to catch and handle exceptions. Python has a hierarchy of built-in exceptions like ZeroDivisionError, NameError, and IOError.
The document discusses Python exception handling. It describes three types of errors in Python: compile time errors (syntax errors), runtime errors (exceptions), and logical errors. It explains how to handle exceptions using try, except, and finally blocks. Common built-in exceptions like ZeroDivisionError and NameError are also covered. The document concludes with user-defined exceptions and logging exceptions.
The document discusses Python exception handling. It defines what exceptions are, how to handle exceptions using try and except blocks, and how to raise user-defined exceptions. Some key points:
- Exceptions are errors that disrupt normal program flow. The try block allows running code that may raise exceptions. Except blocks define how to handle specific exceptions.
- Exceptions can be raised manually using raise. User-defined exceptions can be created by subclassing built-in exceptions.
- Finally blocks contain cleanup code that always runs whether an exception occurred or not.
- Except blocks can target specific exceptions or use a generic except to handle any exception. Exception arguments provide additional error information.
This document discusses exceptions in Python programming. It defines an exception as an event that disrupts normal program flow, such as a runtime error. The document explains how to handle exceptions using try and except blocks. Code is provided to demonstrate catching specific exception types, catching all exceptions, and raising new exceptions. Finally, it notes that exceptions can provide additional error details through arguments.
This document discusses Python errors and exceptions. It explains that there are two types of errors in Python: syntax errors, which occur due to incorrect syntax, and exceptions (also called logical errors), which occur during runtime. It provides examples of common exceptions like ZeroDivisionError, FileNotFoundError, and ImportError. The document also discusses how to handle exceptions using try/except blocks in Python and how to raise custom exceptions. Finally, it covers some advanced exception handling techniques like specifying multiple exceptions, using else and finally blocks, and raising exceptions manually.
This document discusses exception handling in Python. It explains that exceptions occur when runtime errors happen and stop the normal flow of a program. Exceptions can be caused by syntax errors or errors in code that result in an exception even if the syntax is valid, like division by zero. The try and except statement is used to handle exceptions - critical code is placed in the try block and exception handling code is placed in the except block. Multiple except blocks can handle different exceptions. An else block will run only if no exceptions occurred. Finally, a finally block is always executed after try and except to clean up resources. Exceptions can also be manually raised using raise or re-raised after handling.
The document discusses exceptions in Python. It defines exceptions as events that disrupt normal program flow, and explains that Python scripts must either handle exceptions or terminate. It provides examples of different exception types, and describes how to handle exceptions using try and except blocks. Code in the try block may raise exceptions, which are then handled by corresponding except blocks. Finally, an else block can contain code that runs if no exceptions occur.
Python Programming - X. Exception Handling and AssertionsRanel Padon
Â
The document discusses exception handling in Python programming. It defines an exception as an event that occurs during program execution that indicates an error. It describes how Python uses try and except blocks to handle exceptions. The try block contains code that may raise exceptions, and except blocks handle specific exceptions. Finally blocks always execute to cleanup resources, even if no exception occurs. User-defined exceptions should inherit from the built-in Exception class. The raise statement throws exceptions, and assertions act like raise-if statements to validate program logic.
Exceptions in Python represent errors and unexpected events that occur during program execution. There are several ways to handle exceptions in Python code:
1. Try and except blocks allow catching specific exceptions, with except blocks handling the exception.
2. Multiple except blocks can handle different exception types. The else block runs if no exception occurs.
3. Exceptions can be raised manually with raise or instantiated before raising. Finally blocks ensure code runs regardless of exceptions.
Exception Handling in Python allows programs to handle errors and exceptions gracefully. It prevents programs from crashing when errors occur. There are several key aspects of exception handling: exceptions represent errors, try and except blocks catch and handle exceptions, the else block runs if no exception occurs, and finally ensures cleanup code runs regardless of exceptions. User-defined exceptions can also be created to handle custom errors in a program.
Errors in Python programs are either syntax errors or exceptions. Syntax errors occur when the code has invalid syntax and exceptions occur when valid code causes an error at runtime. Exceptions can be handled by using try and except blocks. Users can also define their own exceptions by creating exception classes that inherit from the built-in Exception class. The finally block gets executed whether or not an exception was raised and is used to define clean-up actions. The with statement is also used to ensure objects are cleaned up properly after use.
This document discusses exception handling in Python. It defines errors and exceptions, and describes the different types of errors like syntax errors, semantic errors, type errors, runtime errors, and logical errors. It explains how exceptions occur during program execution. The try and except blocks are described for handling exceptions, with examples given. The raise statement is explained for raising user-defined exceptions. Common built-in exceptions in Python like IOError, ImportError, ValueError and KeyboardInterrupt are also listed.
Understanding Errors and Exceptions in Python
Errors and exceptions are fundamental concepts in Python programming that help developers manage unexpected situations and ensure robust application performance. This guide provides a comprehensive overview of errors and exceptions, their types, and best practices for handling them effectively.
What Are Errors?
Errors are issues that occur during the execution of a program, causing it to stop functioning correctly. They can be broadly categorized into two main types:
Syntax Errors:
These occur when the code violates the rules of the Python language. Syntax errors are detected at compile time, preventing the program from running.
Example:
python
Run
Copy code
print("Hello, World!" # Missing closing parenthesis
Runtime Errors:
These occur during the execution of the program, often due to invalid operations or unexpected conditions. Runtime errors can lead to program crashes if not handled properly.
Example:
python
Run
Copy code
result = 10 / 0 # ZeroDivisionError
What Are Exceptions?
Exceptions are a specific type of runtime error that disrupts the normal flow of a program. They provide a way to signal that an error has occurred and can be caught and handled gracefully. Python has a built-in mechanism for managing exceptions, allowing developers to write more resilient code.
Common Built-in Exceptions
ValueError: Raised when a function receives an argument of the right type but an inappropriate value.
TypeError: Raised when an operation or function is applied to an object of an inappropriate type.
IndexError: Raised when trying to access an index that is out of range in a list or tuple.
KeyError: Raised when a dictionary key is not found.
FileNotFoundError: Raised when trying to access a file that does not exist.
Exception Handling in Python
Python provides a robust mechanism for handling exceptions using try, except, else, and finally blocks:
Try Block: Contains the code that may raise an exception.
Except Block: Catches and handles the exception if it occurs.
Else Block: Executes if the try block does not raise an exception.
Finally Block: Executes regardless of whether an exception occurred, often used for cleanup actions.
Example:
python
Run
Copy code
try:
value = int(input("Enter a number: "))
except ValueError:
print("That's not a valid number!")
else:
print("You entered:", value)
finally:
print("Execution complete.")
Best Practices for Error and Exception Handling
Be Specific: Catch specific exceptions rather than using a generic except clause to avoid masking other issues.
Log Errors: Implement logging to capture error details for debugging and analysis.
Use Custom Exceptions: Define custom exception classes for more meaningful error handling in complex applications.
Graceful Degradation: Ensure that your application can continue to function or provide useful feedback even when errors occur.
đđąđCOPY LINK & PASTE ON GOOGLE https://dr-kain-geera.info/đđ
Wondershare UniConverter is a versatile multimedia tool that combines video conversion, editing, downloading, burning, and transfer capabilities. It's designed to streamline video production by supporting over 1,000 media formats and offering features like video enhancement, basic editing, and batch processing. Essentially, it's a comprehensive video toolbox for various tasks.
Analysis of Quantitative Data Parametric and non-parametric tests.pptxShrutidhara2
Â
This presentation covers the following points--
Parametric Tests
⢠Testing the Significance of the Difference between Means
⢠Analysis of Variance (ANOVA) - One way and Two way
⢠Analysis of Co-variance (One-way)
ď Non-Parametric Tests:
⢠Chi-Square test
⢠Sign test
⢠Median test
⢠Sum of Rank test
⢠Mann-Whitney U-test
Moreover, it includes a comparison of parametric and non-parametric tests, a comparison of one-way ANOVA, two-way ANOVA, and one-way ANCOVA.
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...parmarjuli1412
Â
The document provides an overview of therapeutic communication, emphasizing its importance in nursing to address patient needs and establish effective relationships. THERAPEUTIC COMMUNICATION included some topics like introduction of COMMUNICATION, definition, types, process of communication, definition therapeutic communication, goal, techniques of therapeutic communication, non-therapeutic communication, few ways to improved therapeutic communication, characteristics of therapeutic communication, barrier of THERAPEUTIC RELATIONSHIP, introduction of interpersonal relationship, types of IPR, elements/ dynamics of IPR, introduction of therapeutic nurse patient relationship, definition, purpose, elements/characteristics , and phases of therapeutic communication, definition of Johari window, uses, what actually model represent and its areas, THERAPEUTIC IMPASSES and its management in 5th semester Bsc. nursing and 2nd GNM students
Search Engine Optimization (SEO) for Website SuccessMuneeb Rana
Â
Unlock the essentials of Search Engine Optimization (SEO) with this concise, visually driven PowerPoint.âŻInside youâll find:
â Clear definitions and core concepts of SEO
â A breakdown of OnâPage, OffâPage, and Technical SEO
â Actionable bestâpractice checklists for keyword research, content optimization, and link building
â A quickâstart toolkit featuring Google Analytics, Search Console, Ahrefs, SEMrush, and Moz
â Realâworld case study demonstrating a 70âŻ% organicâtraffic lift
â Common challenges, algorithm updates, and tips for longâterm success
Whether youâre a digitalâmarketing student, smallâbusiness owner, or PR professional, this deck will help you boost visibility, build credibility, and drive sustainable traffic. Download, share, and start optimizing today!
Artificial intelligence Presented by JM.jmansha170
Â
AI (Artificial Intelligence) :
"AI is the ability of machines to mimic human intelligence, such as learning, decision-making, and problem-solving."
Important Points about AI:
1. Learning â AI can learn from data (Machine Learning).
2. Automation â It helps automate repetitive tasks.
3. Decision Making â AI can analyze and make decisions faster than humans.
4. Natural Language Processing (NLP) â AI can understand and generate human language.
5. Vision & Recognition â AI can recognize images, faces, and patterns.
6. Used In â Healthcare, finance, robotics, education, and more.
Owner By:
Name : Junaid Mansha
Work : Web Developer and Graphics Designer
Contact us : +92 322 2291672
Email : [email protected]
This presentation was provided by Nicole 'Nici" Pfeiffer of the Center for Open Science (COS), during the first session of our 2025 NISO training series "Secrets to Changing Behavior in Scholarly Communications." Session One was held June 5, 2025.
Completed Sunday 6/8. For Weekend 6/14 & 15th. (Fathers Day Weekend US.) These workshops are also timeless for future students TY. No admissions needed.
A 9th FREE WORKSHOP
Reiki - Yoga
âIntuition-II, The Chakrasâ
Your Attendance is valued.
We hit over 5k views for Spring Workshops and Updates-TY.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). Iâm Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but thereâs limits As practitioners and masters, we are not allowed to share certain secrets/tools. Some content is designed only for âMastersâ. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
S9/This Weekâs Focus:
* A continuation of Intuition-2 Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
Thx for tuning in. Your time investment is valued. I do select topics related to our timeline and community. For those seeking upgrades or Reiki Levels. Stay tuned for our June packages. Itâs for self employed/Practitioners/CoachesâŚ
Review & Topics:
* Reiki Is Japanese Energy Healing used Globally.
* Yoga is over 5k years old from India. It hosts many styles, teacher versions, and itâs Mainstream now vs decades ago.
* Anything of the Holistic, Wellness Department can be fused together. My origins are Alternative, Complementary Medicine. In short, I call this ND. I am also a metaphysician. I learnt during the 90s New Age Era. I forget we just hit another wavy. Itâs GenZ word of Mouth, their New Age Era. WHOA, History Repeats lol. We are fusing together.
* So, most of you have experienced your Spiritual Awakening. However; The journey wont be perfect. There will be some roller coaster events. The perks are: We are in a faster Spiritual Zone than the 90s. Thereâs more support and information available.
(See Presentation for all sections, THX AGAIN.)
"Hymenoptera: A Diverse and Fascinating Order".pptxArshad Shaikh
Â
Hymenoptera is a diverse order of insects that includes bees, wasps, ants, and sawflies. Characterized by their narrow waists and often social behavior, Hymenoptera play crucial roles in ecosystems as pollinators, predators, and decomposers, with many species exhibiting complex social structures and communication systems.
How to Manage Allocations in Odoo 18 Time OffCeline George
Â
Allocations in Odoo 18 Time Off allow you to assign a specific amount of time off (leave) to an employee. These allocations can be used to track and manage leave entitlements for employees, such as vacation days, sick leave, etc.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
HOW YOU DOIN'?
Cool, cool, cool...
Because that's what she said after THE QUIZ CLUB OF PSGCAS' TV SHOW quiz.
Grab your popcorn and be seated.
QM: THARUN S A
BCom Accounting and Finance (2023-26)
THE QUIZ CLUB OF PSGCAS.
How to Manage Maintenance Request in Odoo 18Celine George
Â
Efficient maintenance management is crucial for keeping equipment and work centers running smoothly in any business. Odoo 18 provides a Maintenance module that helps track, schedule, and manage maintenance requests efficiently.
RE-LIVE THE EUPHORIA!!!!
The Quiz club of PSGCAS brings to you a fun-filled breezy general quiz set from numismatics to sports to pop culture.
Re-live the Euphoria!!!
QM: Eiraiezhil R K,
BA Economics (2022-25),
The Quiz club of PSGCAS
How to Create a Rainbow Man Effect in Odoo 18Celine George
Â
In Odoo 18, the Rainbow Man animation adds a playful and motivating touch to task completion. This cheerful effect appears after specific user actions, like marking a CRM opportunity as won. Itâs designed to enhance user experience by making routine tasks more engaging.
2. Definition
An exception is a runtime error which can be handled by the
programmer. That means if the programmer can guess an error in the
program and he can do something to eliminate the harm caused by
that error then it is called an exception. If error is not handled by
programmer then it is called as error.
All exceptions are represented as classes in python. The exceptions
which are already available in python are called built-in exception.
4. Exception Handling
Purpose of handling errors is to make program robust. It means strong.
Robust program does not terminate in the middle. When there is a error
displays appropriate message to the user and continue execution. When
the errors can be handled they are called exception.
To handle the exception the programmer should perform the following
three steps
Step1: The statement that may cause the exception must be written inside
a âtryâ block
try:
statements
If statement raises an error then it enters into except block otherwise
continues the execution
5. continued
Step2:Programmer should write except block where we should display the exception details to the
user
except exception name:
statements #these statements from handler
Step3:Lastly the programmer should perform clean up actions like closing the files and terminating
any other processes which are running.
finally:
statements
Statements inside the finally block are executed irrespective of whether there is an exception or
not. This ensures that all the opened files are properly closed and all the running processes are
terminated properly.
7. Types of Exception
Exception Class Name Description
Exception Represents any type of exception. All exception are sub classes of this class
ArithmeticError Represents the base class for arithmetic errors like OverflowError,
ZeroDivisionError, FloatingPointError
AssertionError Raised when an assert statement gives error
AttributeError Raised when an attribute reference or assignment fails
EOFError Raised when input() function reaches end of file condition without reading any
data
FloatingPointError Raised when a floating operation fails
GeneratorExit Raised when generators close() method is called
IOError Raised when an input or output operation failed. It raises when the file opened is
not found or when writing data disk is full
ImportError Raised when an import statement fails to find the module being imported
8. continued
Exception Class Name Description
IndexError Raised when a sequence index or subscript is out of range
KeyError Raised when a mapping (dictionary) key is not found in the set of existing
keys
KeyboardInterrupt Raised when the user hits the interrupt key(Control-C, Delete)
NameError Raised when an identifier is not found locally or globally
NotImplementedError Derived from runtimeError
9. Programs on exception
Python program to handle ZeroDivisionError exception
Filename:ep1.py
Python program to handle syntax error given by eval() function
Filename:ep2.py
Python program to handle multiple exception
Filename:ep3.py
10. User Defined Exception
Like the built in exceptions of python user can also create his own
exceptions which are called user defined exception or custom exception.
EXAMPLE: Matainance of minimum balance in account
Steps to define user defined exception
1.Create own exception class and is sub class of built in class Exception
class MyExecption(Exception):
def __init__(self,arg):
self.msg=arg
msg is member of class MyException and is assigned with parameter
received from outside
11. Continued
2. When the programmer suspects the possibility of exception raise own
exception using raise statement
Raise MyExecption(âmessageâ)
3. Programmer must write the code inside a try block and catch the
exception using except block as
try:
code
except MyException as me
print(me)
Python program to illustrate user defined exception
Filename:ep4.py