Java M3
Java M3
Java: Module 3
Exception
Introduction
An exception (or exceptional event) is a problem that arises during the
execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
1. Try-catch blocks:
Try-catch blocks allow you to "try" a block of code and "catch" any
exceptions that are thrown. This is the most common technique for
Java: Module 3 1
handling exceptions in Java.
Syntax
try {
// Code that may throw an exception
} catch (ExceptionType1 e) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e) {
// Code to handle ExceptionType2
} catch (ExceptionType3 e) {
// Code to handle ExceptionType3
}
}
Example
import java.io.FileInputStream;
import java.io.FileNotFoundException;
}
}
}
/*This code will output 'File not Found' if in case the myfile.txt is
in the destination*/
In this case, the catch block simply handles the exception, but you
could also use it to log the exception, display an error message to
the user, or take other appropriate action.
It's important to note that the catch block must specify the type of
exception it is catching. In this example, the catch block catches a
FileNotFoundException, which is a specific type of exception that is
thrown when a file cannot be found. If you want to catch any
exception, you can use the general-purpose Exception class as the
catch parameter.
Java: Module 3 2
2. The "finally" block:
syntax
finally{
}
Example
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");
System.out.println(
"catch : exception not handled.");
}
// Always execute
finally {
System.out.println(
"finally : i will execute always.");
}
// This will not execute
System.out.println("i want to run");
}
}
ouput
Java: Module 3 3
Here, the program throws an exception but not handled by catch so
finally block execute after the try block and after the execution of
finally block program terminate abnormally, But finally block execute
fine.
Syntax
Example
import java.io.FileInputStream;
import java.io.FileNotFoundException;
}
}
Java: Module 3 4
}
else {
System.out.println("Access granted - You are old enough!");
}
}
x = -1;
assert x > 0 : "x is not positive"; // This assertion will fail and throw an AssertionError
System.out.println("This line will not be reached");
}
}
than 0, and since it is, the assertion succeeds and the program
continues to the next line. The second assert statement tests whether
x is positive, and since it is not, the assertion fails and an
AssertionError is thrown.
Note that assert statements are disabled by default in Java, so they
custom exception type that can be thrown and caught in your program.
Java: Module 3 5
Threads
What is a Thread?
Multitasking
In Java, multitasking refers to the ability of a central processing unit
(CPU), or a single core in a multi-core processor, to execute multiple
processes or threads concurrently. This is achieved by allowing each
process or thread to run for a short period of time before interrupting
it and running the next process or thread. This process is known as
"context switching.”
To create a multi-threaded program in Java, you can use the Thread class
Example
Java: Module 3 6
Th create a new thread, you program will either extend Thread or
implement the Runnable interface.
Extend the class and override the run() method. Then, create an
Thread
instance of the class and call the start() method to start the new thread.
Here,the code creates a new thread by extending the Thread class and
overriding the method. The start() method is then called to start
run()
the new thread, which will execute the code in the run() method.
But calling the start() method does not actually cause the code in the
run() method to be executed immediately. Instead, it causes the new
The code creates a new thread by implementing the Runnable interface and
passing an object of the class to the Thread constructor. The start()
Java: Module 3 7
method is then called to start the new thread, which will execute the
code in the run() method.
But calling the start() method does not actually cause the code in the
method to be executed immediately. Instead, it causes the new
run()
States of Thread
https://youtu.be/2HN__CDik_s
Java: Module 3 8
The States of a Thread are:
Runnable
Java: Module 3 9
The second phase of a new-born thread is the execution phase. When the
start() method is called on a the new instance of a thread, it enters
into a runnable state.In the runnable state, thread is ready for
execution and is waiting for availability of the processor (CPU time).
There are many threads that are ready for execution, they all are
waiting in a queue (line).
If all threads have equal priority, a time slot is assigned for each
thread execution on the basis of first-come, first-serve manner by
CPU. The process of allocating time to threads is known as time
slicing. A thread can come into runnable state from running, waiting,
or new states.
Running
Running means Processor (CPU) has allocated time slot to thread for
its execution. When thread scheduler selects a thread from the
runnable state for execution, it goes into running state. Look at the
above figure.
In running state, processor gives its time to the thread for execution
and executes its run method. It is the state where thread performs its
actual functions. A thread can come into running state only from
runnable state.
A running thread may give up its control in any one of the following
situations and can enter into the blocked state.
Java: Module 3 10
1. When sleep() method is invoked on a thread to sleep for specified
time period, the thread is out of queue during this time period.
The thread again reenters into the runnable state as soon as this
time period is elapsed.
3. When wait() method is called on a thread to wait for some time. The
thread in wait state can be run again using notify() or notifyAll()
method.
Waiting (Blocked)
DEAD(terminated)
A thread reaches the termination state because of the following
reasons:
Multi-threaded programming
Java: Module 3 11
Multithreaded programming is a programming paradigm in which a single
process is broken up into two or more threads that can be executed
concurrently, in parallel. Each thread represents a separate flow of
control, and each thread can run a different part of the program, or the
same part of the program with different input data. Multithreaded
programming can be used to increase the performance of a program by
taking advantage of multiple processors or cores, or to allow a program
to perform multiple tasks concurrently, such as downloading data from
the internet while also performing calculations. It can also be used to
simplify the design of a program by allowing different parts of the
program to run concurrently and asynchronously.
Example
This program creates a new WorkerThread and starts it when the main method
is called. The run method of the WorkerThread class will be executed by the
worker thread when it is started. The output of the program will be:
output
Worker thread running!!!
Thread Priorities
In Java, each thread has a priority that determines how much CPU time it
is allocated. Threads with higher priority will be allocated more CPU
time than threads with lower priority. The priority of a thread can be
set using the setPriority
method of the Thread class, and can be any value between MIN_PRIORITY (which
is 1) and MAX_PRIORITY (which is 10). The default priority for a thread is
NORM_PRIORITY ,which is 5.
Java: Module 3 12
// code to be executed by the worker thread
System.out.println("Worker thread running");
}
});
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
}
}
When the program is run, a new thread will be created and the code in
the run method of the Runnable will be executed by the worker thread. The
priority of the thread is set to MAX_PRIORITY (10), which means that it
will be allocated more CPU time than threads with lower priority.
However, it is important to note that the actual allocation of CPU time
to threads is not guaranteed and can depend on various factors, such as
the operating system and the availability of other resources.
Java: Module 3 13