0% found this document useful (0 votes)
1 views25 pages

Module 5 Java

module 5

Uploaded by

Satti Mounica
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)
1 views25 pages

Module 5 Java

module 5

Uploaded by

Satti Mounica
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

Module-5

MANAGING ERRORS AND EXCEPTIONS


INTRODUCTION
The exception handling in java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained. 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.
Exception Hierarchy:

EXCEPTION TYPES
The Exception class is used for exception conditions that the application may need to handle.
Examples of exceptions
include IllegalArgumentException, ClassNotFoundException and NullPointerException.
The Error class is used to indicate a more serious problem in the architecture and should not be
handled in the application code. Examples of errors
include InternalError, OutOfMemoryError and AssertionError.
Exceptions are further subdivided into checked (compile-time) and unchecked (run-time)
exceptions. All subclasses of RuntimeException are unchecked exceptions, whereas all
subclasses of Exception besides RuntimeException are checked exceptions.
This chapter will not be dealing with exceptions of type Error.

Consequences of Uncaught Exception

 Program terminates abruptly


 Stack trace printed
 Resources may not be released

Handling error using EXCEPTIONS handling


An exception is a condition that is caused by a run time error in a program. When the Java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object
and throws it. If the exception object is not caught and handled properly, the interpreter will
display an error message and terminate the program.
The exception handling in java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained. Its purpose is to provide a means to detect
and report an exceptional circumstance to take an appropriate action. The mechanism
incorporates a separate error handling code that performs the following tasks:
1. Find the problem(Hit the exception)
2. Inform that an error has occurred(Throw the exception)
3. Receive the error information(Catch the exception)
4. Take corrective actions(Handle the exception)

The error handling code consists of two segments, one to detect errors and throw exceptions and
the other to catch exceptions and to take appropriate actions.

TYPES OF EXCEPTIONS
Exceptions are categorized into two types:
1. Checked Exceptions: These exceptions are explicitly handled in the code itself with the
help of try-catch blocks. Checked Exceptions are extended from the [Link]
class.
2. Unchecked Exceptions: These exceptions are not essentially handled in the program
code, instead the JVM handles such exceptions. Unchecked Exceptions are extended
form the [Link] class.

Functionality of Checked and Unchecked Exceptions is same, the difference lies only in the
way they are handled.

SYNTAX OF EXCEPTION HANDLING CODE


try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{ }
Example Program:
public class Testtrycatch
{ public static void main(String args[])
{ try
{ int data=50/0; }
catch(ArithmeticException e)
{ [Link](e); }
[Link]("rest of the code...");
}
}

OUTPUT:
Exception in thread main [Link]:/ by zero
rest of the code...

MULTIPLE CATCH STATEMENTS


Multiple Catch statements are used to handle different exceptions when different tasks are to be
performed. When an exception in a try block is generated, the Java treats the multiple catch
statements like cases in a Switch statement. The first statement whose parameter matches the
exception object will be executed, and the remaining statements will be skipped.

Example Program:
public class TestMultipleCatchBlock
{ public static void main(String args[])
{ try
{ int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{ [Link]("task1 is completed"); }

catch(ArrayIndexOutOfBoundsException e)
{ [Link]("task 2 completed"); }
catch(Exception e)
{ [Link]("common task completed"); }
[Link]("rest of the code...");
}
}
Output:task1 completed
rest of the code...
Throwing and Rethrowing Exceptions:
1) Throwing an Exception
Definition

You can use the throw keyword to manually throw an exception in your program.
This is often done to enforce custom validation or to signal an error condition.

Syntax
throw new ExceptionType("Error Message");

Example
public class ThrowExample {
static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
[Link]("Eligible to vote");
}
}

public static void main(String[] args) {


validateAge(15);
[Link]("End of program");
}
}

Output
Exception in thread "main" [Link]: Not eligible to vote
Explanation:

 The program checks if the age is less than 18.


 If true, it throws an ArithmeticException manually using throw.
 Once thrown, the normal flow of the program stops unless handled by a try-catch.

2. Rethrowing an Exception
Definition

Rethrowing means catching an exception and throwing it again — often to let a higher-level
method handle it or to wrap it in another exception type.

Example

public class RethrowExample {

static void readFile() throws Exception {


try {
int data = 50 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
[Link]("Caught inside readFile(): " + e);
throw e; // Rethrowing the same exception
}
}

public static void main(String[] args) {


try {
readFile();
} catch (Exception e) {
[Link]("Caught in main(): " + e);
}
}
}

Output
Caught inside readFile(): [Link]: / by zero
Caught in main(): [Link]: / by zero

Explanation:

 The exception occurs in readFile().


 It’s caught and rethrown using throw e;.
 The rethrown exception is then caught again in the main() method.

USING FINALLY STATEMENT


Java finally block is a block that can handle an exception that is not caught by any of the
previous catch statements. When a finally block is defined, this is guaranteed to execute,
regardless of whether or not an exception is thrown. So, it can be used to execute important
code such as closing connection, stream etc. Java finally block follows try or catch block.

Example Program:
class TestFinallyBlock
{ public static void main(String args[])
{ try
{ int data=25/5;
[Link](data);
}
catch(NullPointerException e)
{ [Link](e); }
Finally
{ [Link]("finally block is always executed"); }
[Link]("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...

THROWING OUR OWN EXCEPTIONS


The Java throw keyword is used to explicitly throw an exception. We can throw either checked
or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw
custom exception.

Syntax: throw exception;


Eg: throw new IOException("sorry device error);
Throw new ArithmeticException();

Example Program: Common Java Exception


class TestCommonException
{ public static void main(String args[])
{ int c=10,d=0;
try
{ if(d==0)
{ throw new ArithmeticException("Division by zero is not possible");
}
}
catch(ArithmeticException h)
{ [Link](h); }
finally
{ [Link]("exception cleared"); }
}
}
Output:
[Link]: Division by zero is not possible
exception cleared
Java throws
throws is a keyword in Java that is used in the signature of a method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.
Syntax:
type method_name(parameters) throws exception_list
where, exception_list is a comma separated list of all the exceptions which a method might
throw.
In a program, if there is a chance of raising an exception then the compiler always warns us
about it and we must handle that checked exception, Otherwise, we will get compile time error
saying unreported exception XXX must be caught or declared to be thrown. To prevent this
compile time error we can handle the exception in two ways:
1. By using try catch
2. By using the throws keyword
We can use the throws keyword to delegate the responsibility of exception handling to the
caller (It may be a method or JVM) then the caller method is responsible to handle that
exception.
class Student {

static void fun() throws IllegalAccessException


{
[Link]("Inside fun(). ");
throw new IllegalAccessException("demo");
}

public static void main(String args[])


{
try {
fun();
}
catch (IllegalAccessException e) {
[Link]("Caught in main.");
}
}
}
Output
Inside fun().
Caught in main.
Explanation: The above example throwing a IllegalAccessException from a method and
handling it in the main method using a try-catch block.
Difference Between throw and throws
The main differences between throw and throws in Java are as follows:
throw throws

It is used to declare that a method might


It is used to explicitly throw an exception.
throw one or more exceptions.

It is used inside a method or a block of code. It is used in the method signature.

It is only used for checked exceptions.


It can throw both checked and unchecked
Unchecked exceptions do not
exceptions.
require throws

The method's caller is responsible for


The method or block throws the exception.
handling the exception.

It forces the caller to handle the


Stops the current flow of execution immediately.
declared exceptions.

public void myMethod() throws


throw new ArithmeticException("Error");
IOException {}

Creating Exception Subclasses: (or) user defined exception


Example Program : User defined Exception
class myexception extends Exception
{ myexception(String s)
{ super(s); }
}
class TestUserException
{ public static void main(String args[])
{ int age=[Link](args[0]);
try
{ if(age>20)
{ throw new myexception("your age exceeds 20"); }
if(age<20)
{ throw new myexception("your age is under 20"); }
else
{ [Link]("eligible for job"); } }
catch(myexception e)
{ [Link]("you are not eligble for job");
[Link](e);
}
}
}

Output :
C:\Users\admin>java TestUserException 25
you are not eligble for job
myexception: your age exceeds 20

C:\Users\admin>java TestUserException 20
eligible for job

C:\Users\admin>java TestUserException 15
you are not eligble for job
myexception: your age is under 20

MULTITHREADING
Concurrency means performing multiple tasks at the same time (simultaneously) or
apparently simultaneously.
In Java, concurrency is achieved using threads.

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Multithreading:

1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of


execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area.

Difference between Multithreading and Multitasking

Multithreading Multitasking
It is a programming concept in which a It is an operating system concept in which
program or process is divided into two or multiple tasks are performed simultaneously.
more sub programs.
It supports execution of multiple parts of a It supports execution of multiple programs
single program simultaneously. simultaneously.
The processor has to switch between different The processor has to switch between different
parts of thread or program programs
It is highly efficient It is less efficient compared to multithreading
A thread is the smallest unit in multithreading A program is smallest unit
It helps in developing efficient programs It helps in developing efficient operating
systems.
Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.


How to create thread

There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

Java Thread Example by extending Thread class

class Multi extends Thread{

public void run(){

[Link]("thread is running...");

public static void main(String args[]){

Multi t1=new Multi();

[Link]();

OUTPUT: Thread is running…


By Implementing Runnable Interface

Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
}
OUTPUT: Thread is running…

Example to create three threads

class Thread_A extends Thread{


public void run(){
for(int k=0;k<100;k++)
[Link]("thread A is running...");
}
class Thread_B extends Thread{
public void run(){
for(int j=0;j<20;j++)
[Link]("thread Bis running...");
}
class Thread_C extends Thread{
public void run(){
for(inti=0;i<10;i++)
[Link]("thread Cis running...");
}
classthreaddemo
{
public static void main(String ae[])
{
Thread_A a=new Thread_A();
Thread_B b=new Thread_B();
Thread_C c=new Thread_C();
[Link]();
[Link]();
[Link]();
}
}

1. Sleep(): method causes the currently executing thread to sleep for the specified number
of milliseconds, subject to the precision and accuracy of system timers and schedulers.
Example:
import [Link].*;
public class ThreadDemo implements Runnable {
public void run() {
for (inti = 10; i< 13; i++) {
[Link]([Link]().getName() + " " + i);
try {
// thread to sleep for 1000 milliseconds
[Link](1000);
} catch (Exception e) {
[Link](e);
}
}
}

public static void main(String[] args) throws Exception {


Thread t = new Thread(new ThreadDemo());
// this will call run() function
[Link]();
Thread t2 = new Thread(new ThreadDemo());
// this will call run() function
[Link]();
}
}
Expected Output:
Thread-0 10
Thread-1 10
Thread-0 11
Thread-1 11
Thread-0 12
Thread-1 12

Other Thread Methods:


public void suspend()
This method puts a thread in the suspended state and can be resumed using resume()
method.
public void stop()
This method stops a thread completely.
public void resume()
This method resumes a thread, which was suspended using suspend() method.
public void wait()
Causes the current thread to wait until another thread invokes the notify().
public void notify()
Wakes up a single thread that is waiting on this object's monitor.

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread schedular 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.
3 constants defiend in Thread class:
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY).


The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example:
class TestMultiPriority1 extends Thread{
public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Synchronization

If multiple threads are simultaneously trying to access the same resource strange results may
occur. To overcome them java synchronization is used. The operations performed on the
resource must be synchronized.

Monitor is the key to synchronization. A monitor is an object that is used as a mutually exclusive
[Link] one thread can own a monitor at a given time. When a thread acquires a lock, it is said
to have entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor (other threads are waiting at that time) .

Code can be synchronized in two ways:

1. Using synchronized Methods


2. Using synchronized Statement

1. Using synchronized Methods :

synchronized void update()

- -- -

When as method is declared as synchronized, java creates a monitor and hands it over to the
thread that calls the method first time. As long as the thread holds the monitor no other thread
can enter the synchronized section of code.
Example:
class Table
{
synchronized void printTable(int n)
{//synchronized method
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}
Output: 5
10
15
20
25
100
200
300
400
500

2. Using synchronized Statement:

This is the general form of the synchronized statement:

synchronized(objRef)

{
// statements to be synchronized
}

objRef is a reference to the object being synchronized. A synchronized block ensures that a
call to a synchronized method that is a member of objRef’s class occurs only after the current
thread has successfully entered objRef’s monitor.

class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}

public class TestSynchronizedBlock1{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}
Output: 5
10
15
20
25
100
200
300
400
500

Inner Classes in Java

An inner class is a class declared inside another class.

They are used to:

 Logically group classes that belong together


 Increase encapsulation
 Access outer class members easily

Types of Inner Classes


Type Description

Non-static (Regular) Inner Class Defined inside another class, associated with its instance

Static Nested Class Defined inside another class, but acts like a static member

1. Regular (Non-Static) Inner Class


class Outer {
private String msg = "Hello from Outer";

class Inner {
void display() {
[Link](msg); // can access outer class members
}
}

void showInner() {
Inner in = new Inner();
[Link]();
}
}

public class TestInner {


public static void main(String[] args) {
Outer outer = new Outer();
[Link]();
}
}

Output:
Hello from Outer

Key Point:
A non-static inner class can access all members (even private) of its outer class.

2. Static Nested Class


class Outer {
static int data = 30;

static class Inner {


void msg() {
[Link]("Data is " + data);
}
}
}

public class TestStaticInner {


public static void main(String[] args) {
[Link] obj = new [Link](); // no outer object required
[Link]();
}
}

Output:

Data is 30

Key Point:
A static nested class can access only static members of the outer class.

Lambda Expressions

Introduced in Java 8, a lambda expression is a shorter way to write anonymous functions


(especially for interfaces with a single abstract method → functional interfaces).

Syntax
(parameter_list) -> { body }

If the body has only one statement, {} can be omitted.

Example 1: Simple Lambda


interface Drawable {
void draw();
}
public class LambdaExample {
public static void main(String[] args) {
Drawable d = () -> [Link]("Drawing with Lambda!");
[Link]();
}
}

Output:

Drawing with Lambda!

Explanation:

 No need for a class that implements Drawable.


 The lambda directly defines the method draw().

Example 2: Lambda with Parameters


interface Addable {
int add(int a, int b);
}

public class LambdaAdd {


public static void main(String[] args) {
Addable ad1 = (a, b) -> (a + b);
[Link]("Sum = " + [Link](10, 20));
}
}

Output:

Sum = 30

Example 3: Lambda with Multiple Statements


interface Sayable {
String say(String name);
}

public class LambdaMulti {


public static void main(String[] args) {
Sayable s = (name) -> {
String msg = "Hello, " + name;
return msg;
};
[Link]([Link]("Java"));
}
}

Output:
Hello, Java

You might also like