0% found this document useful (0 votes)
6 views11 pages

Java Exception Handling & Multithreading Guide

The document covers Exception Handling in Java, detailing the use of try-catch blocks, built-in and user-defined exceptions, and garbage collection. It also discusses multithreading, including thread creation, lifecycle stages, and the Runnable interface. Key concepts such as synchronization, deadlock, and inter-thread communication are also addressed.

Uploaded by

lydialongston
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Java Exception Handling & Multithreading Guide

The document covers Exception Handling in Java, detailing the use of try-catch blocks, built-in and user-defined exceptions, and garbage collection. It also discusses multithreading, including thread creation, lifecycle stages, and the Runnable interface. Key concepts such as synchronization, deadlock, and inter-thread communication are also addressed.

Uploaded by

lydialongston
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-III

Exception Handling: try – catch - throw - throws –- finally – Built-in exceptions - Creating
own Exception classes - garbage collection, finalise -Multithreaded Programming: Thread
Class - Runnable interface – Synchronization – Using synchronized methods – Using
synchronized statement - Interthread Communication – Deadlock

Exception Handling
An exception in Java is an unpredicted condition that arises during the execution of the code
either at compile-time or at run-time.
All the exceptions are handled by the predefined parent class known
as [Link] in Java. The Throwable class has Exception and Error as its subclass.
Exceptions are recoverable and can be recovered using try-catch blocks or throws keywords.
There are mainly two types of exception in Java:
 Built-in Exception
 User Defined Exception

1
Java Exceptions - Try...Catch
Java Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).
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.
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
}
}
}
Finally

2
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
}
}
}

The output will be:


Something went wrong.
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many exception types
available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Sec
urityException, etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {

3
[Link]("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}

The output will be:


Exception in thread "main" [Link]: Access denied - You must be at
least 18 years old.
at [Link]([Link])
at [Link]([Link])

Java Built-in Exceptions


Built-in Exceptions are those exceptions that are pre-defined in Java Libraries. These are the
most frequently occurring Exceptions. An example of a built-in exception can be
ArithmeticException; it is a pre-defined exception in the Exception class of [Link]
package. These can be further divided into two types:
1. Checked Exception
2. Unchecked Exception
[Link] Exceptions:

Checked exceptions are caught at compile time, indicating potentially recoverable errors.
The compiler enforces handling them before runtime.

For instance, accessing a missing file like "[Link]" can throw a FileNotFoundException,
which can be handled using the throws keyword to specify potential exceptions at compile
time.
Class Not Found Exception
The ClassNotFoundException occurs when the Java Virtual Machine cannot locate a required
class, typically triggered by functions like [Link]() or [Link]().
Code:
public class classNotFound
{

4
static String classname = "missingClass";
public static void main() throws ClassNotFoundException
{
[Link](classname);
}
}
Output:
[Link]: missingClass
Compile Time Exception:
The possible exception of type [Link] needs to be handled.
Explanation: Since opening the file can cause IOExceptions, the compiler gives a compile-
time exception, and the code is not compiled.
[Link] Exceptions
An Unchecked Exception is an exception that occurs during runtime, often due to logical
errors or improper usage of functions. These exceptions, also known as Runtime Exceptions,
Arithmetic Exceptions
An ArithmeticException is thrown when the code does the wrong arithmetic or mathematical
operation while executing. Divide by 0 is the most common type of wrong mathematical
operation.
Code:
class arithmeticException
{
public static void main()
{
int a = 10, b = 0;
int c = a / b;
}
Output:
[Link]: / by zero
Explanation: Since we are trying to divide 10 by 0, we are causing a mathematical error.
This is predefined in the ArithmeticException of Exception class in Java. Hence, the code is
throwing the exception.

5
Garbage Collection in Java
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:
protected void finalize(){}

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){[Link]("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
[Link]();
}
}

OUTPUT:
object is garbage collected
object is garbage collected

6
7
Multithreading in Java
Multithreading in Java is an act of executing a complex process using virtual processing
entities independent of each other. These entities are called threads.
Threads in Java are virtual and share the same memory location of the process. As the
threads are virtual, they exhibit a safer way of executing a process.
What are Multitasking and the Types of Multitasking?
Multitasking is an approach to minimize execution time and maximize CPU utilization by
executing multiple tasks simultaneously. You can achieve the process of multitasking in Java
using two methods, as described below.

Multiprocessing in Java
Multiprocessing in Java is purely based on the number of processors available on the host
computer. Every process initiated by the user is sent to the CPU (processor). It loads the
registers on the CPU with the data related to the assigned process.
Multithreading in Java
Multithreading in Java is a similar approach to multiprocessing. However, there are some
fundamental differences between the two. Instead of a physical processor, multithreading
involves virtual and independent threads.

What is a Thread in Java?


A thread is the smallest segment of an entire process. A thread is an independent, virtual and
sequential control flow within a process. In process execution, it involves a collection
of threads, and each thread shares the same memory. Each thread performs the job
independently of another thread.

8
Lifecycle of a Thread in Java
The lifecycle of each thread in Java has five different stages. You will look into each one of
those stages in detail. The Stages of the Lifecycle are mentioned below.
 New
 Runnable
 Running
 Waiting
 Dead

New
The first stage is "New". This stage is where it initiates the thread. After that, every thread
remains in the new state until the thread gets assigned to a new task.
Runnable
The next stage is the runnable stage. Here, a thread gets assigned to the task and sets itself for
running the task.

9
Running
The third stage is the execution stage. Here, the thread gets triggered as control enters the
thread, and the thread performs a task and continues the execution until it finishes the job.
Waiting
At times, there is a possibility that one process as a whole might depend on another. During
such an encounter, the thread might halt for an intermediate result because of its dependency
on a different process. This stage is called the Waiting Stage.
Dead
The final stage of the process execution with Multithreading in Java is thread termination.
After it terminates the process, the JVM automatically declares the thread dead and
terminates the thread. This stage is known as the dead thread stage.
Java, multithreading a thread can be created by the following two ways:
1. By extending the thread class
2. By implementing a Runnable interface
Some of the useful methods of Thread Class that we are going to use:
Creating and Starting Threads
Creating a thread in Java is done like this:
Thread thread = new Thread();
To start the Java thread you will call its start() method, like this:
[Link]();
Thread Subclass
The first way to specify what code a thread is to run, is to create a subclass of Thread and
override the run() method. The run() method is what is executed by the thread after you
call start(). Here is an example of creating a Java Thread subclass:
public class MyThread extends Thread {
public void run(){
[Link]("MyThread running");
}
}
 To create and start the above thread you can do like this:
MyThread myThread = new MyThread();
[Link]();

10
The start() call will return as soon as the thread is started. It will not wait until
the run() method is done. The run() method will execute as if executed by a different CPU.
When the run() method executes it will print out the text "MyThread running".
Runnable Interface Implementation
The second way to specify what code a thread should run is by creating a class that
implements the [Link] interface. A Java object that implements
the Runnable interface can be executed by a Java Thread. How that is done is shown a bit
later in this tutorial.
The Runnable interface is a standard Java Interface that comes with the Java platform.
The Runnable interface only has a single method run(). Here is basically how
the Runnable interface looks:
public interface Runnable() {
public void run();
}
Whatever the thread is supposed to do when it executes must be included in the
implementation of the run() method. There are three ways to implement
the Runnable interface:
1. Create a Java class that implements the Runnable interface.
2. Create an anonymous class that implements the Runnable interface.
Create a Java Lambda that implements the Runnable interface.
All three options are explained in the following sections.
Java Class Implements Runnable

11

You might also like