You are on page 1of 7

Assignment

Subject: Software Construction and development

Submitted to: Ma’am Bisma Islam

Submitted by: Misbah Farooq (35)


Nazal Humayun (39)

Topic: Exception handling making method robust by having


them check their inputs sent from calling objects

Department of Software Engineering Semester V

1
Exception Handling
Exception:
An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program’s instructions.

Types of exceptions:
Exceptions can come in the following two exception classes:

1. Checked exceptions: Also called compile-time exceptions, the compiler checks these
exceptions during the compilation process to confirm if the exception is being handled by
the programmer. If not, then a compilation error displays on the system.
Examples: Checked exceptions include SQLException and ClassNotFoundException.

2. Unchecked exceptions: Also called runtime exceptions, these exceptions occur during
program execution. These exceptions are not checked at compile time, so the programmer
is responsible for handling these exceptions. Unchecked exceptions do not give
compilation errors

Examples: Unchecked exceptions include Null Pointer Exception and Illegal


Argument Exception.

Handling:
Handling is a method to handle/remove the exception.

Exception handling:
Exception handling is the process of responding to unwanted or unexpected events when a
computer program runs. Exception handling deals with these events to avoid the program or system
crashing, and without this process, exceptions would disrupt the normal operation of a program.

Reason of Exception Occurrence:


Exceptions occur for numerous reasons:
• including invalid user input
• code errors
• device failure
• the loss of a network connection insufficient memory to run an application
• a memory conflict with another program
• a program attempting to divide by zero or a user attempting to open files that are
unavailable.

2
How exception is handled?
When an exception occurs, specialized programming language constructs, interrupt hardware
mechanisms or operating system interprocess communication facilities handle the exception.

Examples of exception handling:


The following are examples of exceptions:
➢ SQLException is a checked exception that occurs while executing queries on a database
for Structured Query Language syntax.
➢ ClassNotFoundException is a checked exception that occurs when the required class is
not found – either due to a command-line error, a missing CLASS file or an issue with the
class path.
➢ IllegalStateException is an unchecked exception that occurs when an environment’s state
does not match the operation being executed.
➢ IllegalArgumentException is an unchecked exception that occurs when an incorrect
argument is passed to a method.
➢ NullPointerException is an unchecked exception that occurs when a user tries to access
an object using a reference variable that is null or empty.

How is exception handling used?


If a program has a lot of statements and an exception happens halfway through its execution, the
statements after the exception do not execute, and the program crashes. Exception handling helps
ensure this does not happen when an exception occurs.

Making Methods Robust


A method is like a little program inside a bigger program. It does a specific job when you ask it to.
But what if you ask it to do something it's not prepared for? That's where things can go wrong. To
make our methods robust, we want to check the inputs they get. It's like checking if your students
are giving you numbers when you ask for numbers. If they don't, we want to handle it gracefully,
just like you would in a classroom.

Exception Handling in Methods


Here's how we do it in programming:

Check the Inputs: Before our method starts doing its job, we check if the inputs (the things
we're given) are what we expect. If not, we throw an exception. It's like saying, "Wait a minute,
this is not what I asked for."

3
Handle the Exception: When we throw an exception, we're saying, "Hey, something's
wrong!" But we don't just stop there. We also say what should happen next. For example, if a
student shouts their favorite color, you might say, "That's not an answer. Please try again." In
programming, we can do something similar, like telling the program to try a different approach or
give an error message that makes sense
Why Check Inputs?
When a method receives information or data from another part of the program, we call this
information "input." Checking inputs is like making sure you're getting the right ingredients to
cook a meal. If you get the wrong ingredients, your meal might not taste good, and if you use them
without checking, it could even make someone sick! Similarly, in programming, if a method gets
the wrong input or doesn't check it, it might not work correctly, and it could cause problems in
your program.

Robust:
Robustness, in a general sense, refers to the ability of a system, process, or entity to
maintain its stability, functionality, or performance in the face of various challenges, changes, or
unexpected conditions. It is a quality or property that allows something to endure and adapt
effectively under adverse or uncertain circumstances.
Here's a brief overview of how exception handling works and how it can help make your code
more robust by checking inputs from calling objects:

Throwing Exceptions:
In many programming languages, including Java, C++, Python, and others, you
can use the throw keyword or a similar mechanism to raise an exception when an exceptional
condition is encountered in your code. This typically involves creating an object that represents
the exception (e.g., an instance of an exception class) and throwing it.

Syntax:
void divide(int numerator, int denominator) {
if (denominator == 0) {
throw std::runtime_error("Division by zero");
}
// Perform the division
}

Catching Exceptions:
To handle exceptions, you use a try...catch block or a similar construct in your
code. The try block contains the code that might throw an exception, while the catch block

4
specifies what should happen if an exception of a particular type is thrown. Multiple catch blocks
can be used to handle different types of exceptions.

Syntax:
try {
// Code that may throw exceptions
divide(10, 0);
} catch (const std::runtime_error& e) {
// Handle the exception
std::cerr << "Caught an exception: " << e.what() << std::endl;
}

Handling the Exception:


The catch block handles the caught exception. It specifies the type of exception it
can catch in parentheses, followed by a block of code that handles the exceptional condition.

Multiple Catch Blocks:


You can have multiple catch blocks to handle different types of exceptions. The
first catch block that matches the thrown exception’s type will be executed, and the others will be
skipped.

Syntax:
try {

// code that may throw exceptions


} catch (const SomeExceptionType& e) {
// handle SomeExceptionType
} catch (const AnotherExceptionType& e) {
// handle AnotherExceptionType
} catch (...) {
// handle any other exception that is not caught by previous catch blocks
}

Benefits:
Checking inputs and making methods robust has several benefits:

1. Prevents Errors: It prevents your program from doing unexpected things or crashing
when it gets bad data.
2. Enhances Reliability: Your program becomes more reliable because it handles
invalid input gracefully instead of breaking.

5
3. Improves Security: It can also improve security by preventing malicious input from
causing harm.

Code Example of throw, try and catch:


#include <iostream>
#include <stdexcept>
int main() {
int a, b, c, d;
std::cout << "Enter value of a, b = ";
std::cin >> a >> b;
try {
if (b != 0) {
c = a / b;
std::cout << "Division = " << c << std::endl;
} else {
throw std::runtime_error("Division by zero is not allowed.");
}
if (c == 0) {
d = b / c;
std::cout << "Division = " << d << std::endl;
} else {
throw std::runtime_error("Division by zero result is not allowed.");
}
} catch (const std::runtime_error &ex) {
std::cerr << "Exception caught: " << ex.what() << std::endl;
}
return 0;
}
Code Example of Multi catch:
#include <iostream>
#include <stdexcept>
int main() {
int a;
std::cout << "Enter value of a = ";
std::cin >> a;
try {
if (a == 0) {
throw a; // Throwing an integer
} else if (a == 50) {
throw 'E'; // Throwing a character
} else if (a == 100) {
throw 2.4; // Throwing a float

6
}
} catch (int x) {
std::cout << "a is an integer: " << x << std::endl;
} catch (char x) {
std::cout << "a is a character: " << x << std::endl;
} catch (float x) {
std::cout << "a is a float: " << x << std::endl;
}
return 0;
}

Conclusion:
In programming, making methods robust by checking their inputs is like being a careful chef who
checks the ingredients before cooking. It ensures your program works well, avoids problems, and
keeps everything running smoothly. So, remember to check your inputs to create better and safer
software!

You might also like