0% found this document useful (0 votes)
11 views9 pages

Java Exception Handling & Multithreading

Module 5 covers Exception Handling and Multithreaded Programming in Java. It explains the fundamentals of exception handling, including types of exceptions, the use of try-catch blocks, and creating user-defined exceptions, as well as the basics of multithreading, thread creation, and synchronization. Key concepts include the Java thread model, thread life cycle, and methods for managing thread execution and priorities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

Java Exception Handling & Multithreading

Module 5 covers Exception Handling and Multithreaded Programming in Java. It explains the fundamentals of exception handling, including types of exceptions, the use of try-catch blocks, and creating user-defined exceptions, as well as the basics of multithreading, thread creation, and synchronization. Key concepts include the Java thread model, thread life cycle, and methods for managing thread execution and priorities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 5: Exception-Handling and Multithreaded Programming

Exception Handling in Java


Fundamentals of Exception Handling

An exception is an abnormal condition that occurs during the execution of a program and
disrupts the normal flow of instructions.

Why exception handling is needed:

 Prevents abnormal program termination


 Separates error-handling code from normal logic
 Improves program robustness and reliability

In Java, exception handling is done using five keywords:


try, catch, finally, throw, throws

Exception Types
Java exceptions are mainly classified into:

(a) Checked Exceptions

 Checked at compile time


 Must be either caught or declared using throws
 Examples: IOException, SQLException, FileNotFoundException

(b) Unchecked Exceptions

 Occur at runtime
 Not checked by the compiler
 Subclasses of RuntimeException
 Examples: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException

(c) Errors

 Serious problems that applications should not handle


 Caused by JVM
 Examples: OutOfMemoryError, StackOverflowError

Uncaught Exceptions
An exception is uncaught if it is not handled by a catch block.

 Causes abnormal termination of the program

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

 JVM prints exception name, description, and stack trace

Example:

int a = 10 / 0; // ArithmeticException (uncaught)

Using try and catch


The try block contains code that may generate an exception.
The catch block handles the exception.

Syntax:

try {
// risky code
} catch (ExceptionType e) {
// handling code
}

Example:

try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Division by zero error");
}

Multiple catch Clauses


Multiple catch blocks are used to handle different types of exceptions.

Rules:

 Order should be from most specific to most general


 Only one catch block executes

Example:

try {
int a = [Link];
int b = 10 / a;
} catch (ArithmeticException e) {
[Link]("Arithmetic exception");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index exception");
}

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

Nested try Statements


A try block inside another try block is called a nested try.

Use:

 Handling different exceptions at different levels

Example:

try {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Inner catch");
}
} catch (Exception e) {
[Link]("Outer catch");
}

throw Keyword
The throw keyword is used to explicitly throw an exception.

Syntax:

throw new ExceptionType("error message");

Example:

if (age < 18) {


throw new ArithmeticException("Not eligible to vote");
}

throws Keyword

The throws keyword is used in method declaration to pass exception handling responsibility
to the caller.

Syntax:

returnType methodName() throws ExceptionType

Example:

void readFile() throws IOException {


FileReader fr = new FileReader("[Link]");

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

finally Block

The finally block always executes whether an exception occurs or not.

Uses:

 Closing files
 Releasing resources

Syntax:

try {
// code
} catch (Exception e) {
// handling
} finally {
// cleanup code
}

Java’s Built-in Exceptions


Some commonly used built-in exceptions:

 ArithmeticException
 NullPointerException
 NumberFormatException
 ArrayIndexOutOfBoundsException
 ClassNotFoundException
 IOException

User-Defined Exceptions
Custom exceptions are created by extending the Exception class.

Steps:

1. Create a class that extends Exception


2. Define constructors
3. Use throw to raise the exception

Example:

class InvalidAgeException extends Exception {


InvalidAgeException(String msg) {

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

super(msg);
}
}

class Test {
static void validate(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Age is not valid");
}
}

Multithreaded Programming in Java


Introduction to Multithreaded Programming

Multithreading is a feature of Java that allows multiple parts of a program (threads) to


execute concurrently, improving performance and efficient CPU utilization.

Advantages:

 Better CPU utilization


 Faster execution
 Improved application responsiveness

A thread is a lightweight sub process and the smallest unit of execution.

Java Thread Model


Java uses a pre-emptive, priority-based thread scheduling model.

Key features of Java thread model:

 Each thread has its own execution path


 Threads share the same memory space
 Context switching is handled by JVM
 Thread scheduling depends on priority

Thread life cycle states:

 New
 Runnable
 Running
 Blocked / Waiting
 Terminated (Dead)

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

Main Thread
The main thread is the first thread that starts execution when a Java program runs.

Characteristics:

 Created automatically by JVM


 Controls execution of other threads
 Ends when main() method finishes

Example:

Thread t = [Link]();
[Link](t);

Creating Threads in Java


Threads can be created in two ways:

(a) Extending Thread Class

 Override the run() method


 Call start() to begin execution

Example:

class MyThread extends Thread {


public void run() {
[Link]("Thread running");
}
}

MyThread t = new MyThread();


[Link]();

(b) Implementing Runnable Interface

 Implement run() method


 Pass object to Thread class

Example:

class MyThread implements Runnable {


public void run() {
[Link]("Thread running");
}

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

Thread t = new Thread(new MyThread());


[Link]();

Creating Multiple Threads


Multiple threads can be created by creating multiple Thread objects.

Example:

class Demo extends Thread {


public void run() {
[Link]([Link]().getName());
}
}

Demo t1 = new Demo();


Demo t2 = new Demo();

[Link]();
[Link]();

isAlive() Method

The isAlive() method checks whether a thread is still running.

Syntax:

boolean isAlive()

Returns:

 true – if thread has started and not terminated


 false – otherwise

Example:

[Link]([Link]());

join() Method
The join() method allows one thread to wait until another thread completes execution.

Syntax:

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

[Link]();

Example:

[Link]();
[Link]();
[Link]("Main thread resumes");

Thread Priorities
Thread priority determines the order of execution.

Priority range:

 MIN_PRIORITY = 1
 NORM_PRIORITY = 5 (default)
 MAX_PRIORITY = 10

Methods:

setPriority(int p);
getPriority();

Example:

[Link](Thread.MAX_PRIORITY);

Synchronization
Synchronization is used to control access to shared resources in a multithreaded
environment to avoid inconsistency.

Need for synchronization:

 Prevents data inconsistency


 Avoids race conditions

Types of Synchronization

(a) Synchronized Method


synchronized void display() {
// critical section
}
(b) Synchronized Block
synchronized(this) {
// critical section

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore


Module 5: Exception-Handling and Multithreaded Programming

Example:

class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}

Prof. Sushmitha B R and Prof Swathi R,CSE, EWIT, Bangalore

You might also like