Mod5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Q1. What is exception? Different types of exceptions.

An exception is an unexpected event that occurs during program


execution. It affects the flow of the program instructions which can
cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
- Invalid user input
- Device failure
- Loss of network connection
- Physical limitations (out of disk memory)
- Code errors
- Opening an unavailable file
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 state of the program when the
exception occurred.
Exception Types
 RuntimeException: A runtime exception happens due to a
programming error. They are also known as unchecked exceptions.
These exceptions are not checked at compile-time but run-time.
Examples: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, NumberFormatException

public class UncheckedExceptionExample {


public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e); } } }

 IOException: These exceptions are checked at compile-time. The


compiler ensures that these exceptions are either handled using a
try-catch block or declared in the method signature using the throws
keyword. They represent conditions that are outside the control of
the program (e.g., file not found, database connection issues).
Examples: IOException, SQLException, FileNotFoundException,
ClassNotFoundException
import java.io.File;
import java.io.FileReader;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("nonexistent.txt");
FileReader fr = new FileReader(file);
} catch (Exception e) {
System.out.println("File not found: " + e); } } }

Q2. Explain the keywords try, catch, throw, throws, finally.


Java provides several keywords to handle exceptions effectively. The try,
catch, and throw keywords are integral to exception handling and allow
developers to write robust programs.
1. try
The try block is used to enclose code that might throw an exception.
 If an exception occurs within the try block, it is passed to the
associated catch block.
 If no exception occurs, the try block executes normally, and the catch
block is skipped.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
}

2. catch
The catch block is used to handle exceptions thrown in the associated
try block.
 Each catch block is designed to handle a specific type of exception.
 If an exception occurs, the JVM looks for the matching catch block
based on the type of exception.
Syntax:
try {
// Code that might throw an exception
} catch (SpecificExceptionType e) {
// Code to handle that specific exception
} catch (AnotherExceptionType e) {
// Code to handle another type of exception
}
Multiple catch Blocks
A try block can have multiple catch blocks to handle different exceptions.
They are evaluated in the order they appear.

3. throw
The throw keyword is used to explicitly throw an exception. It can be
used within a method or block to signal that an error condition has
occurred.
 Only one exception can be thrown at a time.
 The throw keyword is followed by an instance of the Throwable
class or its subclasses.
Syntax:
throw new ExceptionType("Error message");

4. throws
The throws keyword is used in a method declaration to specify the
exceptions that might occur.
 Helps delegate the responsibility of handling exceptions to the
caller of the method.
 Used for checked exceptions, which must be declared or handled.
Syntax:
returnType methodName() throws ExceptionType1, ExceptionType2 {
// Code that might throw exceptions
}

5. finally
The finally block is used to execute important cleanup code (like closing
resources), regardless of whether an exception occurs or not.
 Always executes after the try block, even if no exception occurs.
 If a catch block is present, the finally block executes after the
catch block.
Syntax:
try {
// Code that might throw an exception
} finally {
// Cleanup code
}
Example:
public class ExceptionHandlingExample {
static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
System.out.println("Result: " + (a / b));
}

public static void main(String[] args) {


try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Execution completed, resources closed.");
}
}
}

Q3. Program

Q4. Explain thread life cycle in detail.


In Java, a thread passes through several states during its life cycle. These
states are managed by the JVM and provide a clear understanding of
how threads work internally.
During the life time ,thread can be in any one of the following states:
1. Newborn State
 When we create a thread object, the thread is born and it is said to
be in newborn state
 At this state, we can do:
1. schedule it for running using start()
2. kill it using stop()

2. Runnable State
 Runnable state means the thread is ready for execution and is
waiting for availability of the processor.
 Threads in the runnable state are managed by the thread scheduler,
which decides which thread will run based on priority or scheduling
policy.
3. Running State
 Running state means processor has given time to thread for
execution.
 Thread runs till it stop control by its own or preempted by any high
priority thread.
 The thread executes its task in this state.
Transition:
A running thread may move to:
1. Runnable: If it is preempted by a higher-priority thread or the
time slice ends.
2. Blocked: If it is waiting for resources or a lock.
3. Dead: If it completes its execution.

4. Blocked State (Waiting/Timed Waiting)


A thread is in the Blocked state when it is waiting for a resource to
become available or waiting for a specific event.
Subcategories of Blocked State:
1. Waiting: The thread is indefinitely waiting for a signal or message.
2. Timed Waiting: The thread waits for a specified amount of time.
The thread remains in this state until the resource becomes available or
the event occurs.

5. Dead State
 A thread enters the Dead state once its run() method completes or if
it is explicitly stopped.
 A thread cannot be restarted after entering the dead state. Once a
thread is dead, calling start() on it will throw an
IllegalThreadStateException.
Example : class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
try {
Thread.sleep(1000); // Moves to Blocked (Timed Waiting)
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Thread finished execution."); // Moves to Dead
}
}
public class ThreadLifeCycleExample {
public static void main(String[] args) {
Thread t = new MyThread(); // Newborn
t.start(); // Runnable
}
}

Q5. Explain any 5 methods under throw class.


In Java, the Throwable class is the superclass of all errors and exceptions.
It provides several methods that help manage exceptions and errors
effectively. Below are five important methods from the Throwable class,
explained in detail:
1. getMessage()
 Purpose: Returns a detailed message about the exception.
 Use Case: Provides specific information about what caused the
exception, which is helpful for debugging.
Syntax:
public String getMessage()
Example:
java
Copy code
public class GetMessageExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Message: " + e.getMessage());
}
}
}

2. toString()
 Purpose: Returns a string representation of the exception. It includes
the class name and a description of the exception.
 Use Case: Provides a concise representation of the exception for
logging or debugging.
Syntax:
public String toString()
Example:
public class ToStringExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 50; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ToString: " + e.toString());
}
}
}

3. printStackTrace()
 Purpose: Prints the stack trace of the exception to the standard error
stream.
 Use Case: Helps trace the sequence of method calls that led to the
exception, which is invaluable for debugging.
Syntax:
public void printStackTrace()
Example:
public class PrintStackTraceExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length()); // NullPointerException
} catch (NullPointerException e) {
e.printStackTrace(); // Prints the stack trace
}
}
}

4. getCause()
 Purpose: Returns the cause of the exception, if any, or null if the
cause is not set.
 Use Case: Used in chained exceptions to retrieve the underlying
cause.
Syntax:
public Throwable getCause()
Example:
public class GetCauseExample {
public static void main(String[] args) {
try {
Throwable cause = new IllegalArgumentException("Invalid
input");
throw new RuntimeException("Exception occurred", cause);
} catch (RuntimeException e) {
System.out.println("Cause: " + e.getCause());
}
}
}

5. fillInStackTrace()
 Purpose: Records the current stack trace of the thread and returns
the Throwable object.
 Use Case: Useful for re-throwing an exception with an updated stack
trace.
Syntax:
public Throwable fillInStackTrace()
Example:
public class FillInStackTraceExample {
public static void main(String[] args) {
try {
throw new Exception("Original Exception");
} catch (Exception e) {
e.fillInStackTrace();
e.printStackTrace();
}
}
}

Q6. How threads are created explain in detail. (by extends


keyword and runnable interface)
Creating Threads in Java
In Java, threads can be created using two main approaches:
1. Creating Threads by Extending the Thread Class
In this approach, the class extends the Thread class and overrides its
run() method to define the code that the thread will execute.
Steps:
1. Declare a class extending the Thread class
class MyThread extends Thread
{
…………….
}
2. Implement run() method
Override this method to implement code to be executed by the thread
public void run()
{………….//thread code
}
3. Starting a new thread
To actually create and run the thread ,create its object and call the
start() method.
MyThread t1=new MyThread()
t1.start()
Code Example:
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(500); // Pause for 500ms
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread(); // Creating a thread
thread1.start(); // Start the thread

MyThread thread2 = new MyThread();


thread2.start(); // Start another thread
}
}
Key Points of Extending Thread Class:
 The thread object itself contains the task to execute.
 Inherits all methods and properties of the Thread class but cannot
extend any other class.
2. Creating Threads by Implementing the Runnable Interface
In this approach, the class implements the Runnable interface and
defines the task in its run() method. A Thread object is then created to
execute the task.
Steps:
1. Declare a class implementing the Runnable interface
class A implements Runnable
{ ……………. }
2. Implement run() method
Override this method to implement code to be executed by the
thread
public void run()
{………….//thread code}
3. Create object of Thread class and pass object of class which
implements Runnable interface to it
A a1=new A();
Thread t1=new Thread(a1)
4. Call start() method to run a thread
t1.start()
Code Example:
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable thread: " + i);
try {
Thread.sleep(500); // Pause for 500ms
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}
public class RunnableExample {
public static void main(String[] args) {
MyRunnable myTask = new MyRunnable(); // Create a Runnable task
Thread thread1 = new Thread(myTask); // Wrap the task in a Thread
object
thread1.start(); // Start the thread

Thread thread2 = new Thread(myTask); // Another thread with the


same task
thread2.start();
}
}
Key Points of Implementing Runnable Interface:
 Allows a class to extend another class while implementing the
Runnable interface.
 The task is separated from the thread object, making it reusable
by multiple threads.
 Recommended for scenarios where the same task needs to be
executed by multiple threads.

You might also like