0% found this document useful (0 votes)
13 views

Exception Handling

Exception handling OOPs

Uploaded by

kynley
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Exception Handling

Exception handling OOPs

Uploaded by

kynley
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Exception Handling

Java provides robust mechanisms to handle runtime errors through


exception handling and to efficiently perform multiple tasks concurrently
using multithreading. In this document, we'll cover how Java manages
errors gracefully and allows simultaneous execution of multiple threads for
better performance.
1. Exception Handling in Java
An exception is an event that disrupts the normal flow of a program's
execution. In Java, exceptions are objects that encapsulate information about
an error. Exception handling helps to manage these errors gracefully and
continue the program's execution or provide appropriate feedback to the
user.

2. Hierarchy of Exception Classes


All exception classes in Java are part of the java.lang package, and they are
derived from the Throwable class.
 Throwable: The superclass of all errors and exceptions in Java.
o Error: Represents serious system-level issues that are typically
not handled in code (e.g., OutOfMemoryError,
StackOverflowError).
o Exception: Represents recoverable conditions that a program
might want to handle.
 Checked Exceptions: Exceptions that must be caught or
declared in the method signature (e.g., IOException,
SQLException).
 Unchecked Exceptions: Runtime exceptions that occur
due to programming errors and do not need to be declared
(e.g., NullPointerException,
ArrayIndexOutOfBoundsException).

3. Handling Exceptions
Java uses a try-catch block to handle exceptions. If an exception occurs
within a try block, it is caught by the corresponding catch block. If no
exception occurs, the catch block is skipped.
 Syntax:
java
Copy code
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute, whether or not an exception occurs
}
 Example:
java
Copy code
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // Will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution complete.");
}
}
}
In this example, the ArithmeticException is caught by the catch block, and
the finally block is always executed, regardless of whether an exception
occurs.

4. Throwing Exceptions
You can explicitly throw exceptions using the throw keyword. This is useful
when you want to create your own custom exception or handle specific
conditions in a program.
 Example:
java
Copy code
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class Main {


public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
} else {
System.out.println("Access granted.");
}
}

public static void main(String[] args) {


try {
checkAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
In this example, the InvalidAgeException is thrown when the age is less than
18. The checkAge method declares that it might throw an exception, and the
calling code handles it with a try-catch block.

5. Types of Exceptions
 Checked Exceptions: These are exceptions that must be caught or
declared in the method. Example:
java
Copy code
try {
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
 Unchecked Exceptions: These are runtime exceptions that do not
need to be caught or declared. Example:
java
Copy code
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[10]); // Throws
ArrayIndexOutOfBoundsException
}
}

6. Multithreading in Java
Multithreading is the capability of executing multiple threads
simultaneously. A thread is a lightweight process, and Java's built-in
threading mechanism allows you to perform multiple tasks concurrently,
improving the efficiency of your program.

7. Creating Threads in Java


There are two ways to create threads in Java:
1. By extending the Thread class.
2. By implementing the Runnable interface.
A. Extending the Thread class
To create a thread by extending the Thread class, you must override the
run() method, which contains the code that the thread will execute.
 Example:
java
Copy code
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
try {
Thread.sleep(500); // Pauses execution for 500 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the new thread
}
}
In this example, the MyThread class extends the Thread class, and the start()
method creates a new thread that executes the code inside the run()
method.
B. Implementing the Runnable Interface
Another way to create a thread is by implementing the Runnable interface.
This is more flexible because your class can extend another class as well.
 Example:
java
Copy code
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {


public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
In this example, the MyRunnable class implements Runnable, and a Thread
object is created using this class.

8. Thread Life Cycle


A thread in Java goes through the following stages:
1. New: A thread is created but not yet started.
2. Runnable: After calling start(), the thread is ready to run and is
waiting for CPU time.
3. Running: The thread is currently executing.
4. Blocked/Waiting: The thread is waiting for some event to occur (e.g.,
waiting for a resource).
5. Terminated: The thread has finished executing.

9. Thread Synchronization
When multiple threads access shared resources, they can lead to data
inconsistency. Synchronization ensures that only one thread accesses a
resource at a time, preventing conflicts.
 Synchronized Methods: Declaring a method as synchronized
ensures that only one thread can execute it at a time.
 Example:
java
Copy code
class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

class MyThread extends Thread {


Counter counter;

MyThread(Counter counter) {
this.counter = counter;
}

public void run() {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}

public class Main {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
MyThread thread1 = new MyThread(counter);
MyThread thread2 = new MyThread(counter);

thread1.start();
thread2.start();

thread1.join();
thread2.join();

System.out.println("Final count: " + counter.getCount());


}
}
In this example, the increment() method is synchronized, so only one thread
can modify the count at a time, ensuring data consistency.

10. Inter-Thread Communication


Java provides methods like wait(), notify(), and notifyAll() to enable inter-
thread communication, allowing threads to signal each other and coordinate
their execution.
 wait(): A thread that calls wait() gives up the monitor and goes to the
waiting state until it is notified.
 notify(): Wakes up a single thread that is waiting for this monitor.
 notifyAll(): Wakes up all threads that are waiting for this monitor.
 Example:
java
Copy code
class Data {
private int value;

public synchronized void produce(int value) throws InterruptedException {


this.value = value;
System.out.println("Produced: " + value);
notify(); // Notify waiting thread
wait(); // Wait for consumer to consume
}

public synchronized void consume() throws InterruptedException {


System.out.println

You might also like