0% found this document useful (0 votes)
14 views15 pages

Oops Assignment - 3

The document discusses the integration of exception handling and graphics in programming, emphasizing their importance in creating stable and user-friendly graphical applications. It outlines key concepts of exception handling, common exceptions, and the role of graphics in programming, including drawing shapes and managing user interactions. Additionally, it introduces the Standard Template Library (STL) in C++, detailing its components such as containers, algorithms, and iterators, which enhance programming efficiency and productivity.

Uploaded by

arman8119anand
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)
14 views15 pages

Oops Assignment - 3

The document discusses the integration of exception handling and graphics in programming, emphasizing their importance in creating stable and user-friendly graphical applications. It outlines key concepts of exception handling, common exceptions, and the role of graphics in programming, including drawing shapes and managing user interactions. Additionally, it introduces the Standard Template Library (STL) in C++, detailing its components such as containers, algorithms, and iterators, which enhance programming efficiency and productivity.

Uploaded by

arman8119anand
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
You are on page 1/ 15

Assignment of Object Oriented Programming – 3

 Exception Handling and Graphics:


Exception Handling and Graphics are two fundamental concepts in programming that
can work together to improve the stability and functionality of graphical applications.

 Exception Handling

Exception handling refers to the process of managing errors that occur during the
execution of a program. Instead of the program crashing when an error occurs,
exception handling allows the program to catch these errors and take appropriate
actions, such as logging the error, displaying a message to the user, or attempting to
recover from the problem.

The core components of exception handling include:

 Try Block: This section contains code that might throw an exception.
 Catch/Except Block: This part handles the exception if one occurs, allowing the
program to recover or notify the user of the issue.
 Finally Block: This block runs regardless of whether an exception occurred, often
used for cleanup tasks.
 Throw/Raise: This allows a programmer to explicitly trigger an exception.

Exception handling is essential in real-world applications to ensure that errors are


detected and managed without halting the entire program unexpectedly.

 Graphics in Programming

Graphics in programming involves creating and manipulating visual elements such as


images, shapes, colors, and text. This is especially important in applications that require
user interfaces (UIs), games, data visualization, or any program that relies on graphical
output.

Graphics programming can be done using various libraries and frameworks that allow
drawing, animation, and user interaction through graphical components. These libraries
provide tools for handling both 2D and 3D graphics, as well as interfaces for user input
(e.g., mouse clicks, keyboard events).
 Interaction Between Exception Handling and Graphics

 When integrating exception handling into graphical applications, several


challenges and potential errors arise due to the visual nature of the program.
These may include:
 Invalid Drawing Operations: For instance, attempting to draw outside the
allowed boundaries of a canvas or using invalid parameters (like negative values
for coordinates).
 File Handling Issues: Loading images or other assets from files can result in errors
if the file path is incorrect or the file format is unsupported.
 User Input Errors: In interactive applications, users may provide inputs that the
program cannot process correctly, such as entering invalid coordinates or
performing unsupported actions.

In these cases, exception handling becomes crucial to ensure that the program remains
functional even when errors occur. Instead of crashing, the program can display
meaningful error messages, prompt the user for corrective actions, or gracefully recover
from the issue.

For instance, if an error occurs when trying to load a graphical asset like an image,
exception handling can ensure the program provides feedback to the user, such as
notifying them that the file is missing, rather than causing the application to crash
unexpectedly.

 Importance in Graphical Applications

In graphical applications, exception handling plays an important role in improving the


user experience. Graphical programs, especially games or interactive tools, often have
many moving parts, such as rendering complex visuals, handling user inputs, and
managing resources like images and sounds. When one of these parts fails, it’s critical to
handle the failure gracefully.

Without proper exception handling, a simple mistake or missing resource could lead to
the entire program stopping, which could lead to a frustrating user experience.
Exception handling ensures that the program can detect these errors, manage them
appropriately, and keep running or at least exit in a controlled manner.

 Conclusion

2
Exception handling and graphics are intertwined in many types of applications. While
exception handling ensures the program remains stable even when errors occur,
graphics focus on creating and managing visual elements. In graphical applications,
exception handling is especially important for dealing with user errors, invalid graphical
operations, or resource loading issues, ensuring the application provides feedback to
users and avoids crashes. Together, they enhance the robustness and reliability of
interactive and visually rich software.

 List of Common Exceptions:

In programming, exceptions are categorized based on the type of error they represent.
Here are some common exceptions across various programming languages:

1. SyntaxError: Raised when the Python parser encounters a syntax error.


2. IndexError: Raised when trying to access an index in a list or other sequence type
that is out of range.
3. ValueError: Raised when a function receives an argument of the correct type but an
inappropriate value (e.g., passing a string that can’t be converted to a number).
4. TypeError: Raised when an operation or function is applied to an object of
inappropriate type.
5. KeyError: Raised when trying to access a dictionary with a key that does not exist.
6. FileNotFoundError: Raised when trying to open a file that does not exist.
7. ZeroDivisionError: Raised when dividing a number by zero.
8. AttributeError: Raised when an attribute reference or assignment fails (e.g., trying to
call a method on an object that doesn’t have that method).
9. IOError: Raised when an I/O operation (like reading or writing a file) fails.
10. MemoryError: Raised when the program runs out of memory.
11. ImportError: Raised when an imported module cannot be found or loaded.
12. OverflowError: Raised when the result of an arithmetic operation is too large to be
represented.
13. TimeoutError: Raised when a program times out during an operation (e.g., a
network request).
14. ConnectionError: Raised for network-related issues.
15. NotImplementedError: Raised when an abstract method or unimplemented feature
is called.

 Catching Exceptions:
• Catching exceptions is the process of using specific constructs in programming
languages to identify and handle exceptions when they occur.

3
Try Block: Contains code that might raise an exception.
Except Block (Catch Block): Contains code that handles the exception if one occurs.
Else Block: Optional block of code that runs if no exception was raised in the try block.
Finally Block: Code that runs no matter what happens, useful for cleanup actions (e.g.,
closing files, releasing resources).
The general structure for catching exceptions looks like this:

Python:

Java:

 Handling Exceptions

4
• Handling Exceptions:
Handling exceptions means providing a solution to the error or gracefully recovering
from it.
1. Graceful Recovery: In cases where an exception occurs (such as invalid user input),
you can ask the user for new input or correct the problem internally.
2. Logging: When exceptions occur, it’s common to log the error details for debugging
purposes without showing sensitive internal data to the user.
3. Providing Feedback: It’s important to give the user appropriate feedback about the
error without crashing the program. This could be a simple message or a way to
correct the issue (like retrying an action).
4. Raising New Exceptions: Sometimes, you might catch an exception but need to
throw a new one with more context or a custom message.
5. Fallback or Default Values: In some cases, you might provide fallback values or
behaviors if a specific error occurs (e.g., returning a default value if a function
cannot compute a result).

 Key Takeaways

Exceptions are errors that occur during program execution and need to be managed to
prevent crashes.
Catching exceptions allows the program to intercept errors and handle them without
terminating the program unexpectedly.
Handling exceptions involves deciding what to do when an error occurs, such as logging
the error, notifying the user, or providing fallback solutions.

 Text Mode vs. Graphics Mode:


In computer programming, text mode and graphics mode refer to two different ways of
displaying content on a screen:
Text Mode: The screen is divided into a grid of text characters. Each character is drawn
as a grid of pixels, with fixed width and height, typically displaying alphanumeric
characters and symbols. Text mode is efficient for simple user interfaces like command-
line programs and text-based applications, where only text output is required.
Graphics Mode: The screen is treated as a grid of pixels, allowing for the display of
complex images, shapes, colors, and animations. This mode is used for creating
graphical user interfaces (GUIs), games, animations, and interactive applications. Each

5
pixel on the screen can be individually manipulated, offering much more flexibility than
text mode.

 Graphics Mode Functions:

Graphics mode enables the display of a wide variety of visual content, from simple
shapes like lines and rectangles to complex images and animations. Graphics functions
can include:
 Drawing Functions: Used to create visual elements on the screen, such as lines,
circles, and rectangles.
 Pixel Manipulation: Directly changing the color of individual pixels to create
custom graphics, like images or pixel art.
 Windowing: Creating windows or areas within the screen where graphics can be
drawn independently from the rest of the screen.
 Color Management: Setting colors for drawing and filling shapes, manipulating
pixel colors, and using color palettes.
 Buffering: Using off-screen buffers to store images temporarily and then drawing
them all at once to avoid flickering.

 Rectangles and Lines:

 Drawing rectangles and lines are fundamental graphic operations. Most graphics
libraries provide built-in functions to draw these shapes:

 Rectangles: A rectangle is defined by its top-left corner coordinates and its width
and height. In graphics mode, rectangles are drawn by specifying these
parameters.

Functions for drawing rectangles often allow you to specify not just the coordinates and
dimensions, but also fill color, border color, and other styles.

6
Lines: A line is defined by two points: the start and the end coordinates. Lines can be
drawn with various thicknesses, colors, and styles (dotted, dashed, solid).
Line drawing is often optimized to follow algorithms like Bresenham’s line algorithm to
ensure smooth rendering.

 Polygons
A polygon is a closed figure made up of multiple straight lines. The defining
characteristic of a polygon is that the first and last points are connected.

Drawing Polygons: In graphics mode, polygons are created by specifying a series of


connected points (vertices) in a coordinate system. Most graphics libraries provide
functions that allow for the creation of both regular and irregular polygons, including
options for filling them with color.
Types of Polygons: Common types include triangles, squares, pentagons, and more
complex polygons with many sides.

 Inheritance :

Inheritance is a core concept in object-oriented programming (OOP), allowing new


classes to inherit properties and methods from existing classes. In graphics, inheritance
can be used to create reusable and extensible graphic objects or entities.

 Base Class: A generic graphic object class, such as Shape, could have methods for
drawing, filling, and transforming basic shapes.
 Derived Classes: More specific shapes, such as Rectangle, Circle, and Polygon,
can inherit from the Shape class. These subclasses can override or extend base
class methods with their own specialized behavior (e.g., a rectangle might have a
method to compute its area).

Example Use of Inheritance: A base Shape class could have a method to draw the shape,
and then each specific shape (e.g., Rectangle, Line, Polygon) could inherit from it and
implement the details of how to draw itself, while also being able to utilize the common
functionality like setting colors or moving positions.

7
 Sound and Motion:

In graphics and interactive applications, sound and motion are critical for enhancing the
user experience, particularly in games, animations, and multimedia applications.

 Sound:
Sound functions are used to play music, sound effects, and voice recordings in a
program.
Waveform-based Sound: Basic sound can be generated using waveforms (sine, square,
etc.), which can be used for simple sound effects.
Sampling: For more realistic sound, digital sound samples (like .wav, .mp3) are used.
These can be played when certain events occur, like a user interaction or an animation
step.

Sound can also be used in combination with animation or graphics to sync visual and
auditory events, like the sound of an object bouncing when it hits the ground.

 Motion:
Animation: Creating motion involves updating the position of graphical objects over
time. This is achieved by repeatedly redrawing objects at different coordinates, which
gives the illusion of motion.
Smooth Motion: For smooth animation, techniques like frame-by-frame animation or
tweening (interpolating between two keyframes) can be used.
Physics-based Motion: Advanced motion techniques involve simulating physical
properties like gravity, velocity, and collision detection, which are especially useful in
games.

 Text in Graphics Mode:


In graphics mode, text rendering refers to the process of displaying textual information
as part of graphical content, often in combination with shapes, colors, and animations.

8
Text Rendering Functions: Text can be displayed at specific positions on the screen, with
control over font size, style, color, and alignment. Some graphics libraries support rich
text formatting with different fonts, sizes, and even images mixed into the text.

Text in Games and GUIs: In graphical applications, text might be used for:

Displaying labels, buttons, and titles.


Showing scores, health bars, or other game statistics.
Providing dynamic text that changes based on user input or game state (e.g., displaying
“Game Over” when the player loses).
Anti-aliasing and Font Rendering: In more advanced graphics modes, techniques like
anti-aliasing can be used to make text appear smoother and more readable, especially in
high-resolution displays.

 Conclusion

The transition from text mode to graphics mode allows for far more dynamic and
visually engaging applications. Drawing rectangles, lines, and polygons is essential for
creating the foundational shapes in graphics programming, while concepts like
inheritance help organize and manage the complexity of drawing objects in an efficient
and reusable way. Sound and motion are crucial in creating interactive, immersive
experiences, and text in graphics mode brings versatility to visual communication in
graphical applications. Together, these elements form the core of graphical
programming, enabling the creation of visually rich and interactive software.

 Standard Template Library (STl):

The Standard Template Library (STL) is a powerful library in C++ that provides a
collection of generic classes and functions. The library is designed to provide commonly
used data structures (containers) and algorithms, making it easier to write efficient and
reusable code. The STL is part of the C++ Standard Library and significantly improves
programming productivity.

Overview of Standard Template Library

9
The STL consists of four key components:

1. Containers: These are data structures that store collections of data. They define how
data is stored and accessed.
2. Algorithms: These are functions that operate on containers. They provide
functionality such as searching, sorting, modifying, and other common operations.
3. Iterators: These are objects used to access and traverse the elements in containers.
They act as the interface between algorithms and containers.
4. Function Objects (Functors): These are objects that can be called as functions.
Functors can be passed to algorithms as a form of customization.
5. Allocators: These manage memory for container elements and allow customization
of memory allocation.

 Containers in STL:

Containers are the data structures in STL that store elements. They are implemented as
templates and can hold any data type. The primary categories of containers are:

1. Sequence Containers: These containers store elements in a linear sequence. They


allow random access to elements and can grow dynamically.

 Vector: Dynamic array that allows fast random access and efficient appends.
 Deque (Double-Ended Queue): Similar to vector, but allows fast insertions and
deletions at both ends.
 List: Doubly linked list allowing efficient insertions and deletions from both ends
but slower random access.

2. Associative Containers: These store elements in a sorted order based on keys, and
allow fast access using those keys.

 Set: A collection of unique keys, sorted automatically.


 Map: A collection of key-value pairs, sorted by key, where each key is unique.

10
 Multiset: Similar to set, but allows duplicate keys.
 Multimap: Similar to map, but allows duplicate keys.

3. Unordered Containers: These store elements in an unordered fashion, typically


allowing faster average lookup times compared to associative containers.

Unordered Set: A collection of unique keys with no specific order.


Unordered Map: A collection of key-value pairs with no specific order.

4. Container Adapters: These provide a different interface or functionality for an


existing container.

 Stack: A LIFO (Last-In, First-Out) container adapter, typically implemented on top


of a deque or vector.
 Queue: A FIFO (First-In, First-Out) container adapter, typically implemented on
top of a deque.
 Priority Queue: A container adapter where elements are retrieved in priority
order (typically implemented with a heap).

 Algorithms in STL:

STL algorithms are generic functions that can operate on any container (as long as they
provide the appropriate iterators). These algorithms abstract common tasks like
searching, sorting, and modifying data. Key algorithms in STL include:

 Sorting: Functions like sort(), stable_sort() help to sort elements in containers.


 Searching: Functions like find(), binary_search() allow searching for elements.
 Manipulating: Functions like reverse(), fill(), remove() help manipulate or modify
data.
 Non-modifying: Functions like count(), for_each(), and equal() that perform
operations without modifying the data.

11
These algorithms are designed to work with iterators, so they can be used with any
container type that supports the required iterator operations.

 Iterators in STL:

An iterator is an object that points to an element in a container. Iterators are used by


STL algorithms to access container elements in a uniform way. They provide a common
interface for all containers, allowing the same algorithms to work with different types of
containers.

Types of Iterators:
 Input Iterator: Reads from a container, one element at a time.
 Output Iterator: Writes to a container, one element at a time.
 Forward Iterator: Allows reading and writing in one direction.
 Bidirectional Iterator: Allows reading and writing in both directions (forward and
backward).
 Random Access Iterator: Allows random access to elements, similar to pointer
arithmetic.

 Other STL Elements:

1. Function Objects (Functors): These are objects that can be used as if they were
functions. They are typically used to customize algorithms (like sorting). A function
object defines the operator() method, which makes an instance of the class callable.
2. Allocators: STL provides allocators that allow customization of memory allocation for
container elements. While the default allocator uses the global new and delete, a
custom allocator can be implemented for special memory management.

 Container Classes in STL:

Each container class in the STL has its own characteristics. Here’s a closer look at some
of the container classes:

12
1. Vector:
Provides dynamic resizing, similar to an array.
Supports fast random access and efficient appends to the end.
Inefficient for insertions and deletions at the beginning or middle.

2. Deque:
A double-ended queue.
Allows fast insertion and deletion at both ends.
Slower random access compared to vectors but more flexible.

3. List:
A doubly linked list.
Allows fast insertion and deletion at any position but does not support fast random
access.

4. Set:
Stores unique elements in a sorted order.
Uses a balanced tree structure to provide logarithmic time complexity for operations
like search, insertion, and deletion.

5. Map:
Stores key-value pairs with unique keys in sorted order.
Uses a balanced tree to provide fast lookups, insertions, and deletions by key.

6. Unordered Containers:
Store elements in an unordered manner, often implemented using hash tables.
Provide faster average time complexity for lookups and insertions but without
maintaining order.

 General Theory of Operation:


Containers store data and expose iterators to access and manipulate that data.

13
Algorithms operate on containers via iterators, making them independent of the
underlying container type.
Iterators abstract the traversal of data, providing a uniform way to interact with various
container types.
Function Objects enable customization of certain algorithmic behaviors, like sorting or
filtering.
Allocators manage memory allocation, allowing flexibility in how data is stored in
containers.

 Vectors in STL

The vector class is one of the most commonly used container classes in STL. It provides a
dynamic array, which automatically resizes when elements are added.

Key features of vectors:


 Dynamic Size: Vectors can grow or shrink dynamically as elements are added or
removed.
 Efficient Access: Vectors provide fast random access to elements through the []
operator or the at() method.
 Efficient Appending: Inserting elements at the end of the vector is efficient, but
inserting at the beginning or in the middle can be slow.
 Memory Management: Vectors manage memory automatically, but you can
control their capacity using reserve() and shrink_to_fit() to optimize
performance.

 Conclusion
The Standard Template Library (STL) provides powerful tools for writing efficient,
reusable, and maintainable C++ programs. By utilizing containers, algorithms, and
iterators, developers can work with various data structures in a consistent manner,
allowing for flexibility and optimization. The use of STL reduces the need to implement
data structures and algorithms from scratch and helps in writing more readable and
efficient code.

14
15

You might also like