0% found this document useful (0 votes)
7 views

cse425 assignment

Uploaded by

tasfia2829
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

cse425 assignment

Uploaded by

tasfia2829
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

NORTH SOUTH UNIVERSITY

Department of Electrical and Computer


Engineering

Exception & Event Handling in


Programming Languages

Md. Rakibul Islam Reshad 2021723642

Instructor: Fazlul Hasan Siddiqui

CSE 425

Section 10
Abstract:
Exception and event handling are essential concepts in programming languages, allowing
developers to create robust, maintainable, and error-resistant applications. Programming
languages offer mechanisms that deal with errors and asynchronous events in a systematic
manner, promoting application reliability and responsiveness. Accordingly, the article
examines the evolution, design, and implementation of exception/event handling mechanisms
in programming languages adopting an array of programming paradigms. This paper aims to
discuss some of the important paradigms and compare the approaches towards the
implementation of handlers. Real-world examples and scenarios highlight the necessity of
these features for enhancing software quality and user experience.

Introduction:
Software systems today have become complex enough that robust mechanisms for handling a
variety of unexpected situations are needed to be put into use by the ease of which programs
are executed. Software systems have some inherent error conditions like invalid user inputs,
hardware failures, network disruptions, etc. Moreover, asynchronous events, such as sensor
data updates or user interactions, also require mechanisms for providing responsive and flexible
program behavior. To conquer this issue, most of the programming languages come with a
construct known as Exception and Event Handling.

Exception handling:
first introduced in languages such as PL/I and ADA and in fact has become a standard feature
in many modern-day programming languages like Java, Python and C++. It allows you to
manage runtime errors in a structured way by separating out the error-handling logic from the
normal program flow. Another case is event handling, which allows applications to respond
dynamically in real time, so they can react to various external stimuli, such as events generated
via graphical user interfaces (GUIs) or hardware input devices.

The paper investigates the theoretical principles, historical development, and practical
applications of exception and event handling. The survey explores critical design choices, such
as control flow constructs, language features, and inter-language interaction. It also includes
real-world examples and diagrams that illustrate how these mechanisms interact to influence
software reliability and usability.

In C++ and Java, this is called Exception handling. It helps keep software systems stable. It
promotes code readability, maintainability, and robustness — with a separation of error-
handling code from the primary logic.

Importance of Exception Handling:


A runtime error can be anything from an invalid input to a hardware failure. Without a
systematic method for addressing such errors, programs are prone to crashing or generating
erratic output. Exception handling ensures that these errors are handled efficiently, maintaining
application stability and providing meaningful feedback to the end-user or developers.

C++ Exception Handling:


Hardware-generated errors (crossing a watermark or fault line) are called exceptions. Custom
exception classes provide users with the ability to describe particular error conditions. On error,
the throw statement throws an exception that is caught by the matching catch block.
Example:
#include <iostream>
#include <stdexcept>

void divide(int a, int b) {


if (b == 0) {
throw std::runtime_error("Division by zero");
}
std::cout << "Result: " << a / b << std::endl;
}

int main() {
try {
divide(10, 0);
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}

Java Exception Handling:


ava exception handling is a built-in mechanism in Java Language. C# is also using try, catch
and throw keywords just like C++ but possesses some more features including finally block
and checked exceptions. Unlike runtime exceptions, checked exceptions must either be
declared in the method signature or caught explicitly, allowing for compile-time error
checking.

Example:
public class ExceptionExample {
public static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
System.out.println("Result: " + (a / b));
}

public static void main(String[] args) {


try {
divide(10, 0);
} catch (ArithmeticException e) {
System.err.println("Error: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}
}
}
Comparison of C++ and Java Exception Handling

1. Syntax and Features:


● Java requires exceptions to be derived from the Throwable class while C++ allows any
exception type including primitives.
● C++ lacks the finally block (it uses RAII for resource management), but Java provides
it for cleanup.
● They are generally unchecked C++ exceptions, which help developers write flexible
applications, but at the cost of requiring more discipline. Java’s checked exceptions are
a compile time enforcer of explicit handling.
2. Performance:
● One of the main differences in design between C++ exceptions and exceptions in other
languages is that C++ exceptions have very low runtime overhead — an important point
in systems programming.
● Because Java runs into a managed runtime, there is more overhead with its exception
handling and a higher number of checks.
3. Error Management Philosophy:
● C++ sacrifices some safety in exchange for performance and also flexibility, deferring
responsibility to the developer.
● Java takes an approach that emphasizes reliability and developer-friendly error
handling, leading to less chance of unhandled exceptions.

To sum up, C++ vs Java exception handling both offer powerful exception handling
mechanisms that cater to their design philosophies. The key point about each language will
give developers an insight about how to use these languages in real example.

Exception Handling in Python and Ruby:


Python and Ruby take an approach to exception handling that favors simplicity and developer
productivity. They both have structured approaches to identify, manage, and recover from
runtime errors, leading to more robust application behavior.

Python Exception Handling:


Python is a lesson in exception handling with the try, except, else, and finally blocks which
gives developers a nice syntax to use. By default, Python exceptions are classes that inherit
from a base class called Exception, which allows programmers to build custom exception
hierarchies.
Example:
def divide(a, b):
try:
result = a / b
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print(f"Result: {result}")
finally:
print("Execution completed.")

# Example usage
divide(10, 0)
divide(10, 2)
Ruby Exception Handling:
Basically, Ruby’s exception handling mechanism is using begin, rescue, else, and ensure
blocks, analogous to Python’s exception handling structure. In ruby exceptions are object
objects that inherits from the class called StandardError and developers can create there own
exception classes for handling specific errors.

Example:
def divide(a, b)
begin
result = a / b
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
else
puts "Result: #{result}"
ensure
puts "Execution completed."
end
end

# Example usage
divide(10, 0)
divide(10, 2)

Comparison of Python and Ruby Exception Handling:

1. Syntax and Features:


● Both languages share a similar block structure but Python uses try/except and Ruby
uses begin/rescue.
● Python has except to catch exceptions and Ruby has rescue.
● They both provide else for executing code when no exceptions are raised and
finally/ensure for clean-up.
2. Error Hierarchies:
● In Python, exceptions inherit from the BaseException class, while in Ruby they inherit
from Exception or StandardError.
● Both offer extensibility, permitting custom exceptions.
3. Philosophy:
● Python promotes readability and explicitness, which is in keeping with its “There
should be one — and preferably only one — obvious way to do it” philosophy.
● Exceptions in Ruby are super flexible and expressive, which is in line with Ruby’s
motto of developer happiness and productivity.

Overall, both Python and Ruby provide thorough and easy-to-understand exception handling
systems that achieve a balance of simple-to-use vs flexible. These cater to the purpose of
making resilient applications more readable and elegant.

Introduction to Event Handling:


This is a programming paradigm that allows software applications to react dynamically to user
actions, system signals, or external stimuli. It is essential for creating interactive and real-time
applications, where responsiveness and adaptability are paramount.
Importance of Event Handling:
A modern software system must be able to synchronize user interactions and system events
especially in graphical user interfaces (GUIs), real-time monitoring systems and web
applications. This is where an effective handling of the event comes into play to enable the
capturing and processing of the input and an action in response in a timely manner for a better
UX and application efficiency.

Introduction to Event Handling Systems Architecture:


Most event handling systems have primarily three parts:
1. Event Sources:
● These are the sources of events: user inputs (mouse clicks, keyboard presses),
sensors, network signals, etc.
● For example, a button click in a GUI application is an event source.
2. Event Listeners:
● Listeners are abstractions that keep watching certain event sources for specific triggers.
● They express interest in an event, and perform pipe handlers when the event occurs.
● For example: A ButtonClickListener in GUI framework.
3. Event Handlers:
● Handlers are functions or methods that run in response to particular events.
● They contain the necessary logic to handle the event.
● For instance, a handler saves a form upon clicking the "Submit" button.

Workflow of an Event Handling System:


● An event then is generated by the event source when it uses a specific trigger.
● Event listeners detect an event and trigger the associated handlers.
● The handlers do some appropriate logic, completing the event-processing cycle.

Real-World Example:

Event Handling in a GUI Framework:


● It is the event source, which is the button.
● The button is hooked up to a listener, such as ButtonClickListener.
● The handler gets executed. When the event is fired, and the listener detects a click event.
● The handler runs some logic, like showing a message or running a computation.

Example in Java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class EventHandlingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling Example");
JButton button = new JButton("Click Me");

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Event Handling with Java


Event handling in Java is a cornerstone of its event-driven programming model, enabling
developers to create responsive and interactive applications. It leverages robust frameworks
like Abstract Window Toolkit (AWT) and Swing, which provide built-in support for event-
driven architectures. Java’s event-handling model is based on a delegation approach, where
specific objects handle events generated by other objects.

The Event-Driven Programming Model in Java:


While the event-driven model of Java relies on handing off events to be processed by event
handlers. Now we are going for explaining the 4 basic components of all event systems: event
sources, event objects, event listeners, and event handlers.

Event Sources: These are event-producing objects, like buttons, sliders, text fields, etc. in a
GUI. For example: Clicking a button or pressing a key creates an event.
Event Objects: Whenever an event happens, the system wraps its details in an event object. So
the ActionEvent class handles things like letting the program know that a button was just
pressed.

Event Listeners: They can be interfaces that specify methods for handling certain kinds of
events. From here, developers implement these interfaces to specify what happens when the
specific event occurs.For instance, the ActionListener interface handles action events.

Event Handlers: These are event specific methods invoked that execute application logic
when an event is fired.

The Event-Driven Programming Model:


Java uses an event-driven programming model based on the delegation event model. When an
event fires, the source creates an event object, and the listener's corresponding event handler
method handles it.

AWT and Swing Libraries

1. AWT (Abstract Window Toolkit):


● AWT was the very first GUI framework Java had, consisting of a set of common
components such as buttons, text fields, and windows.
● The java. awt. event package defines the interfaces and classes for event handling.
2. Swing:
○ Swing extends AWT with a more comprehensive set of GUI components and
more versatile event handling.
○ Swing components are part of the javax.swing package and include elements
like JButton, JLabel, and JTextField.
Example of Event Handling in Java
import javax.swing.*;
import java.awt.event.*;

public class ButtonClickExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling Example");
JButton button = new JButton("Click Me");

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In this case, you created a button using Swing and registered an ActionListener to capture click
events on this button. When we click on the button it calls the actionPerformed method which
prints a message on the Console.

Event Handling in C#:


C# uses the event-driven programming model, where events are raised based on user actions.
This approach allows developers to create modular and reusable event-driven applications.

Delegates and the event Keyword

1. Delegates:
● Delegates are type-safe function pointers that specify the signature of event handler
methods.
● They underlie event handling, associating methods with events.
2. event Keyword:
○ This makes sure only the event source can fire the event delegate.

Example of Event Handling in C#


using System;

public class Button


{
public delegate void ClickEventHandler(object sender, EventArgs e);
public event ClickEventHandler Click;

public void OnClick()


{
if (Click != null)
{
Click(this, EventArgs.Empty);
}
}
}

public class Program


{
public static void Main(string[] args)
{
Button button = new Button();

button.Click += (sender, e) => {


Console.WriteLine("Button clicked!");
};

button.OnClick();
}
}

In this example, a custom Button class defines a Click event using a delegate. The event is
raised by calling the OnClick method, and an event handler is attached to respond to the event.

Advantages of Event Handling in C#

1. Type Safety:
○ A delegate is much like a function pointer; it provides method type safety on an
event and ensures that the event handler methods have the correct signature,
minimizing potential runtime errors.
2. Modularity:
○ The event-driven model encourages separation of concerns by decoupling
consumers from a source of events.
3. Extensibility:
○ Developers define custom events and handlers, tailoring the model to meet the
varying requirements of different applications.

Conclusion:
Final Thoughts Exception and event handling are crucial components of contemporary
programming languages, empowering developers to create resilient, maintainable, and
interactive applications. Handling runtime errors in C++, Java, Python, and Ruby or providing
responsive UIs in Java and C#, show that structured approaches to error and event management
are all handled with these mechanisms. Developers are able to construct software systems that
are reliable and adaptable to user demands and real-world contexts, by taking advantage of the
strengths of each language.
Citations
● Goodenough, J. B. (1975). Exception handling: Issues and a proposed notation.
Communications of the ACM, 18(12), 683-696.
● Buhr, R. J. A., & Harji, Y. M. (1996). Event-based programming systems. IEEE
Transactions on Software Engineering, 22(9), 603-616.
● Stroustrup, B. (2000). Exception safety in C++: A pragmatic look at code. ACM
SIGPLAN Notices, 35(5), 141-150.
● Reenskaug, T. (1979). Models-Views-Controllers. Xerox PARC Memo.
● Geary, D. M., & Horstmann, C. S. (2007). Core Java, Volume II - Advanced Features.
Pearson.
● Schildt, H. (2018). Java: The Complete Reference. McGraw-Hill Education.
● Sun Microsystems. (1997). Java AWT Reference. Sun Microsystems Documentation.
● Oracle. (2024). Java Swing Tutorial. Retrieved from Oracle Java Documentation.

You might also like