Mod5
Mod5
Mod5
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));
}
Q3. Program
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.
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
}
}
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();
}
}
}