Unit 5
Unit 5
Note: With the help of exception handling we can detect and handle the exceptions gracefully so that the
normal flow of the program can be maintained.
The summary is depicted via visual aid below as follows:
Java Exception Hierarchy
All exception and error types are subclasses of the class Throwable, which is the base class of the
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user
programs should catch. NullPointerException is an example of such an exception. Another
branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError is an example of such an error.
The below figure demonstrates the exception hierarchy in Java:
Major Reasons Why an Exception Occurs: Exceptions can occur due several reasons, such as:
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Out of bound
• Null reference
• Type mismatch
• Opening an unavailable file
• Database errors
• Arithmetic errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors
are usually beyond the control of the programmer, and we should not try to handle errors.
Difference Between Exception and Error
Types of Java Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
1. Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to handle common errors
during program execution.
1.1 Checked Exceptions
Checked exceptions are called compile-time exceptions because these exceptions are checked at
compile-time by the compiler. Examples of Checked Exception are listed below:
1. ClassNotFoundException: Throws when the program tries to load a class at runtime but the class
is not found because its not present in the correct location or it is missing from the project.
2. InterruptedException: Thrown when a thread is paused and another thread interrupts it.
3. IOException: Throws when input/output operation fails
4. InstantiationException: Thrown when the program tries to create an object of a class but fails
because the class is abstract, an interface, or has no default constructor.
5. SQLException: Throws when there’s an error with the database.
6. FileNotFoundException: Thrown when the program tries to open a file that doesn’t exist
1.2 Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check
these exceptions at compile time. In simple words, if a program throws an unchecked exception, and
even if we didn’t handle or declare it, the program would not give a compilation error. Examples of
Unchecked Exception are listed below:
1. ArithmeticException: It is thrown when there’s an illegal math operation.
2. ClassCastException: It is thrown when you try to cast an object to a class it does not belongs to.
3. NullPointerException: It is thrown when you try to use a null object (e.g. accessing its methods
or fields)
4. ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an
invalid index.
5. ArrayStoreException: It happens when you store an object of the wrong type in an array.
6. IllegalThreadStateException: It is thrown when a thread operation is not allowed in its current
state
2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases,
users can also create exceptions, which are called “user-defined Exceptions“.
Methods to Print the Exception Information
Try-Catch Block
A try-catch block in Java is a mechanism to handle exception. The try block contains code that might
thrown an exception and the catch block is used to handles the exceptions if it occurs.
finally Block
The finally Block is used to execute important code regardless of weather an exception occurs or not.
Note: finally block is always executes after the try-catch block. It is also used for resource cleanup.
Handling Multiple Exception
We can handle multiple type of exceptions in Java by using multiple catch blocks, each catching a
different type of exception.
How Does JVM Handle an Exception?
Default Exception Handling: When an Exception occurs, the JVM Creates an exception object
containing the error name, description, and program state. Creating the Exception Object and
handling it in the run-time system is called throwing an Exception. There might be a list of the
methods that had been called to get to the method where an exception occurred. This ordered list of
methods is called Call Stack. Now the following procedure will happen.
1. The run-time system searches the call stack for an Exception handler
2. It starts searching from the method where the exception occurred and proceeds backward through
the call stack.
3. If a handler is found, the exception is passed to it.
4. If no handler is found, the default exception handler terminates the program and prints the stack
trace.
Look at the below diagram to understand the flow of the call stack.
Concurrent Programming
Concurrent Programming: This means that tasks appear to run simultaneously, but under the
hood, the system might really be switching back and forth between the tasks. The point of
concurrent programming is that it is beneficial even on a single processor machine.
Concurrent Programming on Single Processor Machine:
1. Suppose the user needs to download five images and each image is coming from a different
server, and each image takes five seconds, and now suppose the user download all of the first
images, it takes 5 seconds, then all of the second images, it takes another 5 seconds, and so forth,
and by the end of the time, it took 25 seconds. It is faster to download a little bit of image one,
then a little bit of image two, three, four, five and then come back and a little bit of image one and
so forth.
2. If it takes 5 seconds for each one, and breaking it up into little chunks, the total sum is still 25
seconds. Then why is any faster to download it concurrently.
3. It is because when the image from the first server is called and it takes 5 seconds, not because
incoming bandwidth is maxed out, but because it takes a while for the server to send it to the user.
Basically, the user sits around waiting most of the time. So, while the user is waiting for the first
image, he might as well be starting to download the second image. So, if the server is slow, by
doing it in multiple threads concurrently, one can download additional images without much extra
time.
4. Now eventually, if one downloads a lot of images concurrently, the incoming bandwidth might get
maxed out and then adding more threads won’t speed it up, but up to a point, it’s kind of free.
5. Besides speed, another advantage is decreased latency. Doing a little bit at a time decreases
latency, so the user can see some feedback as things go along.
Need of Concurrent Programming
• Threads are useful only when the task is relatively large and pretty much self contained. When the
user needs to perform only a small amount of combination after a large amount of separate
processing, there’s some overhead to starting and using threads. So if the task is really small, one
never get paid back for the overhead.
• Also, as mentioned above, threads are most useful when the users are waiting. For instance, while
one is waiting for one server, the other can be reading from another server.
Basic Steps for Concurrent Programming
1. Firstly to queue a task. The call executor service dots new fixed thread pool and supplies a size. This
size indicates the maximum number of simultaneous tasks. For instance, if one add a thousand things
to the queue but the pool size is 50, then only 50 of them will be running at any one time. Only when
one of the first fifty finishes executing will 51st be taken up for execution. A number like 100 as pool
size won’t overload the system.
2. The user then has to put some tasks of a runnable type to the tasks queue. Runnable is just a single
interface that has one method called the run. System calls the run method at the appropriate time when
it switches back and forth among the tasks by starting a separate thread.
3. Execute method is a little bit of misnomer because when a task is added to the task in the queue that is
created above with executors dot new fixed thread pool, it doesn’t necessarily start executing it right
away. It starts executing when one of those executing simultaneously(pool size) finishes execution.
Advantages:
• Loose Coupling: Since a separate class can be reused, it promotes loose coupling.
• Constructors: Arguments can be passed to constructors for different cases. For example,
describing different loop limits for threads.
• Race Conditions: If the data has been shared, it is unlikely that a separate class would be used as
an approach and if it does not have a shared data, then no need to worry about the race conditions.
Disadvantages:
It was a little bit inconvenient to call back to the main application. A reference had to be passed
along the constructor, and even if there is access to reference, only public methods(pause method
in the given example) in the main application can be called.
Multithreading
• Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
• Threads can be created by using two mechanisms :
• Extending the Thread class
• Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available
in the Thread class. A thread begins its life inside run() method. We create an object of our new class and
call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
// Java code for thread creation by extending the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
} } }
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we
instantiate a Thread object and call start() method on this object.
// Java code for thread creation by implementing the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
} } }
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can still
extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides
some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
3. Using runnable will give you an object that can be shared amongst multiple threads.