Wawtg 20240327-053234
Wawtg 20240327-053234
Error:
• Error is an illegal operation performed by the user which results in the abnormal working
of the program.
• Programming errors often remain undetected until the program is compiled or executed.
• Some of the errors inhibit the program from getting compiled or executed.
• Thus errors should be removed before compiling and executing.
Types Of Errors:
1. Run time error
2. Compile time error
➢ Run Time errors occur or we can say, are detected during the execution of the program.
➢ Sometimes these are discovered when the user enters an invalid data or data which is not
relevant.
➢ Runtime errors occur when a program does not contain any syntax errors but asks the
computer to do something that the computer is unable to reliably do.
➢ During compilation, the compiler has no technique to detect these kinds of errors.
➢ It is the JVM (Java Virtual Machine) that detects it while the program is running.
➢ To handle the error during the run time we can put our error code inside the try block and
catch the error inside the catch block.
➢ Compile Time Errors are those errors which prevent the code from running because of
an incorrect syntax such as a missing semicolon at the end of a statement or a missing
bracket, class not found, etc.
➢ These errors are detected by the java compiler and an error message is displayed on the
screen while compiling.
➢ Compile Time Errors are sometimes also referred to as Syntax errors. These kind of
errors are easy to spot and rectify because the java compiler finds them for you.
➢ The compiler will tell you which piece of code in the program got in trouble and its best
guess as to what you did wrong.
➢ Usually, the compiler indicates the exact line where the error is, or sometimes the line
just before it, however, if the problem is with incorrectly nested braces, the actual error
may be at the beginning of the block. In effect, syntax errors represent grammatical
errors in the use of the programming language.
Logical Error: A logic error is when your program compiles and executes, but does the wrong
thing or returns an incorrect result or no output when it should be returning an output. These
errors are detected neither by the compiler nor by JVM.
Exception:
➢ In Java, Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the program’s
instructions.
➢ Exceptions can be caught and handled by the program. When an exception occurs
within a method, it creates an object.
➢ This object is called the exception object.
➢ It contains information about the exception, such as the name and description of the
exception and the state of the program when the exception occurred.
• 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.
2. User-Defined Exceptions:
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’.
Java try and catch
➢ The try statement allows you to define a block of code to be tested for errors while it is
being executed.
➢ The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
Example
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
}
Nested Try block in Exception:
class NestedTry {
// main method
public static void main(String args[])
{
// Main try block
try {
// initializing array
int a[] = { 1, 2, 3, 4, 5 };
The throw statement is used together with an exception type. There are many exception types
available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Securit
yException, etc:
Example:
else {
Finally Block
The finally block in java is used to put important codes such as clean up code e.g. closing the
file or closing the connection. The finally block executes whether exception rise or not and
whether exception handled or not. A finally contains all the crucial statements regardless of the
exception occurs or not.
Case 2: When the exception rises and handled by the catch block
Case 3: When exception rise and not handled by the catch block
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");
}
}
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.
Each process has an address in memory. In other words, each process allocates a separate
memory area.
A process is heavyweight.
Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
A thread is lightweight.
• 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.
try {
System.out.println(
+ " is running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
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.
{
try {
System.out.println(
+ " is running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
class Multithread {
Thread object
object.start();
}
}
A thread in Java at any point of time exists in any one of the following states. A thread
lies only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when the thread is in this state. When a thread lies in the new state, its code
is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a
thread might actually be running or it might be ready to run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but
currently the lock is acquired by the other thread. The thread will move from the blocked
state to runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join()
method. It will move to the runnable state when other thread will notify or that thread
will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-
out parameter. A thread lies in this state until the timeout is completed or until a
notification is received. For example, when a thread calls sleep or a conditional wait, it is
moved to a timed waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:
Because it exits normally. This happens when the code of the thread has been entirely executed
by the program.
Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled
exception.
In Java, to get the current state of the thread, use Thread.getState() method to get the current state
of the thread. Java provides java.lang.Thread.State class that defines the ENUM constants for the
state of a thread, as a summary of which is given below:
1. New
2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual
machine but it may be waiting for other resources from the operating system such as a processor.
3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is
waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized
block/method after calling Object.wait().
4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the
following methods:
LockSupport.park
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting
state due to calling one of the following methods with a specified positive waiting time:
Thread.sleep
Object.wait with timeout
LockSupport.parkNanos
LockSupport.parkUntil
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
try {
Thread.sleep(1500);
catch (InterruptedException e) {
e.printStackTrace();
System.out.println(
try {
Thread.sleep(200);
catch (InterruptedException e) {
e.printStackTrace();
// state.
System.out.println(
thread1.start();
System.out.println(
+ thread1.getState());
// state.
System.out.println(
+ thread2.getState());
thread2.start();
System.out.println(
"State of thread2 after calling .start() method on it - "
+ thread2.getState());
try {
Thread.sleep(200);
catch (InterruptedException e) {
e.printStackTrace();
System.out.println(
+ thread2.getState());
try {
thread2.join();
catch (InterruptedException e) {
e.printStackTrace();
System.out.println(
"State of thread2 when it has finished it's execution - "
+ thread2.getState());
Thread Methods:
1. Wait()
2. Sleep()
3. Notify()
4. Resume()
5. Suspend()
6. Stop()
Thread Exceptions:
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of
the given thread.
The method throws IllegalArgumentException if the value newPriority goes out of the range,
which is 1 (minimum) to 10 (maximum). constants defined in Thread class:
Java Synchronization is used to make sure by some synchronization method that only one thread
can access the resource at a given point in time.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization is used to coordinate and ordering of the execution of the threads in a
multi-threaded program. There are two types of thread synchronization are mentioned below:
• Mutual Exclusive
• Cooperation (Inter-thread communication in Java)Inter-thread Communication in
Java
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the imple3)
3) notifyAll() method
synchronized keyword is used to make the class or method thread-safe which means only one
thread can have lock of synchronized method and use it, other threads have to wait till the lock
releases and anyone of them acquire that lock.
It is important to use if our program is running in multi-threaded environment where two or more
threads execute simultaneously. But sometimes it also causes a problem which is called
Deadlock. Below is a simple example of Deadlock condition.