0% found this document useful (0 votes)
40 views22 pages

Java Exception Handling & Multithreading Guide

The document covers key concepts in Java programming, focusing on exception handling and multithreading. It explains types of exceptions (checked, unchecked, and errors), the try-catch-finally structure, and the creation of custom exceptions. Additionally, it outlines multithreading with threads and runnable interfaces, detailing thread methods and states.

Uploaded by

satyamsurineda
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)
40 views22 pages

Java Exception Handling & Multithreading Guide

The document covers key concepts in Java programming, focusing on exception handling and multithreading. It explains types of exceptions (checked, unchecked, and errors), the try-catch-finally structure, and the creation of custom exceptions. Additionally, it outlines multithreading with threads and runnable interfaces, detailing thread methods and states.

Uploaded by

satyamsurineda
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

1.

Exception Handling
What is an Exception?

 An exception is an event that disrupts normal program flow.


 Types:
1. Checked Exceptions → Checked at compile-time (e.g., IOException,
SQLException).
2. Unchecked Exceptions → Occur at runtime (e.g., ArithmeticException,
NullPointerException).
3. Errors → Serious problems, generally not handled (e.g., OutOfMemoryError).

Try-Catch-Finally

 Try → block where exception may occur.


 Catch → block to handle exception.
 Finally → block that executes always, whether exception occurs or not.

public class ExceptionDemo {


public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // ArithmeticException
} catch (ArithmeticException e) {
[Link]("Error: Division by zero");
} finally {
[Link]("Finally block executed");
}
}
}

Throw and Throws

 throw → explicitly throw an exception.


 throws → declare that a method may throw an exception.

class Demo {
static void checkAge(int age) throws Exception {
if (age < 18) throw new Exception("Age must be >= 18");
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (Exception e) {
[Link]([Link]());
}
}
}

Custom Exceptions
class MyException extends Exception {
MyException(String msg) { super(msg); }
}

class Test {
static void validate(int num) throws MyException {
if (num < 0) throw new MyException("Number must be positive");
}
public static void main(String[] args) {
try {
validate(-5);
} catch (MyException e) {
[Link]([Link]());
}
}
}

🔹 2. Multithreading in Java
What is a Thread?

 A thread is a lightweight process that executes code independently.


 Java supports multithreading to achieve concurrent execution.

Creating Threads

1. By Extending Thread Class

class MyThread extends Thread {


public void run() { // entry point of thread
for(int i=0;i<5;i++){
[Link]("Thread running: " + i);
}
}
}
public class TestThread {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // start new thread
}
}
2. By Implementing Runnable Interface

class MyRunnable implements Runnable {


public void run() {
for(int i=0;i<5;i++){
[Link]("Runnable thread: " + i);
}
}
}
public class TestRunnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
}
}

Thread Methods

Method Description
start() Starts the thread and calls run()
run() Contains thread execution code
sleep(ms) Pauses thread for specified milliseconds
join() Waits for a thread to finish before continuing
yield() Suggests scheduler to switch thread
setPriority() Sets thread priority (1-10)
isAlive() Checks if thread is running

Thread States

1. New → created but not started


2. Runnable → ready to run, waiting for CPU
3. Running → currently executing
4. Waiting/Blocked → waiting for a resource
5. Terminated → finished execution

Example: Multithreading with Sleep


class MyThread extends Thread {
public void run() {
for(int i=1;i<=5;i++){
[Link]("Thread: " + i);
try { [Link](500); } catch (InterruptedException e) { }
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
}
}

✅ Summary Table

Concept Key Points


Exception Handling try-catch-finally, throw, throws, custom exceptions
Checked vs Unchecked Compile-time vs runtime exceptions
Multithreading Concurrent execution using Thread or Runnable
Thread Methods start(), run(), sleep(), join(), yield(), setPriority()
Thread States New, Runnable, Running, Waiting/Blocked, Terminated

1. Concepts of Exception Handling


What is an Exception?

 An exception is an event that occurs during program execution that disrupts the normal
flow of instructions.

Types of Exceptions

1. Checked Exceptions
o Checked at compile-time.
o Must be handled using try-catch or declared using throws.
o Example: IOException, FileNotFoundException.
2. Unchecked Exceptions
o Occur at runtime.
o Not required to handle, but can be caught.
o Example: ArithmeticException, NullPointerException.
3. Errors
o Serious problems not usually handled in code.
o Example: OutOfMemoryError, StackOverflowError.

Key Terms

Term Description
Term Description
Try Block Code that might throw an exception
Catch Block Handles the exception thrown by try block
Finally Block Executes regardless of exception occurrence
throw Used to explicitly throw an exception
throws Declares the exceptions a method might throw

Example
public class ExceptionDemo {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // may throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Error: Division by zero");
} finally {
[Link]("Finally block executed");
}
}
}

🔹 2. Benefits of Exception Handling


1. Separation of Error Handling Code from Regular Code
o Makes program logic cleaner and easier to read.
2. Maintains Normal Flow of Program
o Even if an error occurs, the program can handle it gracefully and continue
execution.
3. Propagates Errors to a Higher Level
o Using throws, a method can pass an exception to the caller for handling.
4. Group and Handle Different Exceptions Separately
o Different catch blocks allow specific handling of each exception type.
5. Improves Program Reliability
o Prevents program from crashing abruptly due to runtime errors.

Example: Multiple Exception Handling


public class MultiCatchDemo {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 100; // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
[Link]("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
} finally {
[Link]("Finally always executes");
}
}
}

✅ Summary Table

Concept Key Points


Exception Event disrupting normal program flow
Checked vs
Compile-time vs runtime exceptions
Unchecked
Try-Catch-Finally Structure to handle exceptions
throw/throws Explicitly throw or declare exceptions
Clean code, program continuity, reliability, error propagation, specific
Benefits
handling

1. Termination vs Resumptive Models


1. Termination Model

 Definition: After an exception occurs, control is transferred to an exception handler,


and normal execution does not resume at the point where the exception occurred.
 This is Java’s model.
 Once the exception is handled, the program continues from the handler or next
statement after try-catch.

Example in Java:

public class TerminationDemo {


public static void main(String[] args) {
try {
int a = 10, b = 0;
int c = a / b; // exception occurs
[Link]("This line will not execute");
} catch (ArithmeticException e) {
[Link]("Division by zero caught");
}
[Link]("Program continues after catch");
}
}

Output:
Division by zero caught
Program continues after catch

2. Resumptive Model

 Definition: After an exception occurs, control returns to the point of exception and
allows the program to resume execution.
 Java does not support this model.
 Found in some languages like Common Lisp or PL/I.

Key Difference:

Feature Termination Model Resumptive Model


Control after exception Moves to handler Returns to point of exception
Supported in Java ✅ Yes ❌ No
Complexity Simple Complex
Reliability High Can be risky

🔹 2. Java Exception Hierarchy


Java exceptions are organized as a tree, rooted at Throwable.

[Link]

[Link]
├── Error (unchecked, serious system errors)
│ ├── OutOfMemoryError
│ ├── StackOverflowError
│ └── ...

└── Exception
├── Checked Exceptions (compile-time)
│ ├── IOException
│ ├── SQLException
│ └── ClassNotFoundException

└── RuntimeException (unchecked)
├── ArithmeticException
├── NullPointerException
├── ArrayIndexOutOfBoundsException
└── IllegalArgumentException

Key Points

 Throwable → base class for all errors and exceptions.


 Error → serious problems, not meant to be caught.
 Exception → problems that can be handled.
o Checked → compile-time, must handle.
o Unchecked (RuntimeException) → runtime, optional to handle.

✅ Summary Table

Topic Key Points


Termination Exception transfers control to handler; execution does not resume at
Model exception point; used in Java
Resumptive
Exception handling resumes at point of exception; not supported in Java
Model
Exception Root = Throwable; subclasses: Error (system-level), Exception
Hierarchy (checked/unchecked)

1. try
 The try block contains code that might throw an exception.
 Must be followed by at least one catch block or a finally block.

try {
int a = 10, b = 0;
int c = a / b; // may throw ArithmeticException
}

🔹 2. catch
 The catch block handles the exception thrown by the try block.
 Syntax: catch(ExceptionType e)

try {
int a = 10, b = 0;
int c = a / b;
} catch (ArithmeticException e) {
[Link]("Error: Division by zero");
}

 Multiple catch blocks can handle different exceptions:

try {
int[] arr = new int[5];
arr[10] = 100;
} catch (ArithmeticException e) {
[Link]("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
}

🔹 3. throw
 Used to explicitly throw an exception.
 Can throw either checked or unchecked exceptions.

public void checkAge(int age) {


if (age < 18) {
throw new ArithmeticException("Age must be 18 or above");
}
}

🔹 4. throws
 Declares exceptions that a method might throw, passing responsibility to the caller.
 Used for checked exceptions.

public void readFile() throws IOException {


FileReader fr = new FileReader("[Link]"); // may throw IOException
}

 Caller must handle the exception:

try {
readFile();
} catch (IOException e) {
[Link]("File not found");
}

🔹 5. finally
 Block that always executes, regardless of whether an exception occurred.
 Often used to release resources like files, DB connections, or streams.

try {
int a = 10, b = 0;
int c = a / b;
} catch (ArithmeticException e) {
[Link]("Division by zero");
} finally {
[Link]("Finally block always executes");
}
Quick Example Combining All
import [Link].*;

class Demo {
void checkFile(String filename) throws IOException {
FileReader fr = new FileReader(filename);
[Link]("File opened successfully");
}
}

public class Main {


public static void main(String[] args) {
Demo d = new Demo();
try {
[Link]("[Link]"); // may throw IOException
int a = 10, b = 0;
if(b == 0) throw new ArithmeticException("b cannot be zero"); //
throw
int c = a / b;
} catch (IOException e) {
[Link]("File error: " + [Link]());
} catch (ArithmeticException e) {
[Link]("Arithmetic error: " + [Link]());
} finally {
[Link]("Cleanup or final block executed");
}
}
}

✅ Summary Table

Keyword Usage
try Block of code to monitor for exceptions
catch Handles specific exception types thrown by try
throw Explicitly throws an exception
throws Declares exceptions a method might throw
finally Executes always, used to release resources

1. Built-in Exceptions in Java


Java provides a rich set of predefined exception classes, mainly under the [Link] package.
These are divided into checked and unchecked exceptions.

1. Checked Exceptions

 Must be handled using try-catch or declared with throws.


 Examples:
| Exception | Description |
|-----------|------------|
| IOException | Input/output errors (file not found, stream issues) |
| SQLException | Database access errors |
| ClassNotFoundException | Class not found dynamically |
| FileNotFoundException | File does not exist |

Example:

import [Link].*;

public class CheckedDemo {


public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}
}
}

2. Unchecked Exceptions (Runtime Exceptions)

 Occur during runtime, handling is optional.


 Examples:
| Exception | Description |
|-----------|------------|
| ArithmeticException | Divide by zero |
| NullPointerException | Accessing null reference |
| ArrayIndexOutOfBoundsException | Array index invalid |
| IllegalArgumentException | Illegal method argument |

Example:

public class UncheckedDemo {


public static void main(String[] args) {
int a = 10, b = 0;
int c = a / b; // ArithmeticException
}
}

🔹 2. Creating Your Own Exception Subclasses


Steps
1. Extend Exception for a checked exception or RuntimeException for an unchecked
exception.
2. Provide constructors to set a custom message.
3. Throw the exception using throw keyword.

Example: Custom Checked Exception


class MyException extends Exception {
MyException(String message) {
super(message); // pass message to Exception class
}
}

public class TestCustomException {


static void checkAge(int age) throws MyException {
if (age < 18) {
throw new MyException("Age must be 18 or above");
} else {
[Link]("Age OK");
}
}

public static void main(String[] args) {


try {
checkAge(15);
} catch (MyException e) {
[Link]("Caught custom exception: " + [Link]());
}
}
}

Example: Custom Unchecked Exception


class MyRuntimeException extends RuntimeException {
MyRuntimeException(String message) {
super(message);
}
}

public class TestRuntime {


public static void main(String[] args) {
throw new MyRuntimeException("This is a custom runtime exception");
}
}

✅ Summary Table

Topic Key Points


Built-in Exceptions Checked (compile-time) vs Unchecked (runtime)
IOException, FileNotFoundException, ArithmeticException,
Common Built-in
NullPointerException
Topic Key Points
Exceptions
Custom Exception Extend Exception (checked) or RuntimeException (unchecked)
Throwing Custom
Use throw new MyException("message")
Exception
Handling Custom
Use try-catch for checked exceptions
Exception

1. String Handling in Java


Strings in Java

 Strings are objects of the String class in [Link].


 Strings are immutable → once created, their value cannot be changed.

Common String Operations


public class StringDemo {
public static void main(String[] args) {
String str = "Hello Java";

// Length
[Link]([Link]()); // 10

// Concatenation
String s2 = str + " World";
[Link](s2); // Hello Java World

// Character at position
[Link]([Link](0)); // H

// Substring
[Link]([Link](6)); // Java

// Equals
[Link]([Link]("Hello Java")); // true

// Contains
[Link]([Link]("Java")); // true

// Convert to uppercase/lowercase
[Link]([Link]()); // HELLO JAVA
}
}

StringBuffer & StringBuilder

 Mutable strings for efficient modification.


 StringBuffer → synchronized, thread-safe
 StringBuilder → non-synchronized, faster

StringBuilder sb = new StringBuilder("Hello");


[Link](" World");
[Link](sb); // Hello World

🔹 2. Exploring [Link] Package


 Contains utility classes like Collections, Date/Time, Random, Scanner etc.
 Commonly used classes:

Class Purpose
ArrayList, LinkedList Dynamic arrays / linked lists
HashMap, TreeMap Key-value mapping
HashSet, TreeSet Unique elements, sorted elements
Collections Utility methods for collections
Date, Calendar Date and time operations
Random Generate random numbers
Scanner Input from console / files

Example: ArrayList
import [Link].*;

public class UtilDemo {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Java");
[Link]("Python");
[Link]("C++");

for(String lang : list) {


[Link](lang);
}

[Link]("Python");
[Link]("After removal: " + list);
}
}

🔹 3. Differences Between Multithreading and Multitasking


Feature Multithreading Multitasking
Definition Multiple threads within a single process Multiple processes run concurrently
Feature Multithreading Multitasking
run concurrently
Unit of
Thread Process
Execution
Resource Processes do not share memory
Threads share memory & resources
Sharing directly
Overhead Less overhead (lightweight) More overhead (heavyweight)
Speed Faster due to shared resources Slower due to context switching
Multiple tasks in a program: GUI + Running a browser + music player +
Example
background computation IDE simultaneously

✅ Summary

1. String Handling → Immutable strings, StringBuffer/StringBuilder for mutable


strings.
2. [Link] Package → Provides collections, utilities, date/time, random numbers, and
scanner classes.
3. Multithreading vs Multitasking → Threads vs processes, shared memory vs separate
memory, lightweight vs heavyweight.

1. Thread Lifecycle in Java


A thread in Java can be in one of the following states:

State Description
New Thread object is created but start() is not called yet.
Runnable Thread is ready to run and waiting for CPU allocation.
Running Thread is currently executing its run() method.
Waiting Thread is waiting indefinitely for another thread to signal it.
Timed Waiting Thread waits for a specified time using methods like sleep(ms), join(ms).
Blocked Thread is waiting to acquire a lock for synchronization.
Terminated Thread has finished execution or stopped.

Lifecycle Diagram:

New --> Runnable --> Running --> Terminated


| ^
v |
Waiting/Blocked/Timed Waiting
🔹 2. Creating Threads in Java
Method 1: Extending Thread Class
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread running: " + i);
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // starts a new thread
}
}

Method 2: Implementing Runnable Interface


class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Runnable thread: " + i);
}
}
}

public class RunnableDemo {


public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
}
}

🔹 3. Thread Priorities
 Threads in Java have priorities from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY).
 Default priority is 5 (NORM_PRIORITY).
 Higher priority threads are more likely to get CPU time, but scheduling depends on JVM
and OS.

Setting Thread Priority


class MyThread extends Thread {
MyThread(String name) { super(name); }
public void run() {
[Link](getName() + " is running with priority " +
getPriority());
}
}

public class ThreadPriorityDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.MAX_PRIORITY); // 10

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

Key Points

1. Thread moves from New → Runnable → Running → Terminated.


2. Can create threads by extending Thread or implementing Runnable.
3. Priorities suggest scheduling preference but do not guarantee order.
4. Use sleep(), join(), and synchronization for timed waiting and coordination.

1. Synchronizing Threads
 Problem: Multiple threads accessing shared resources may cause data inconsistency.
 Solution: Use synchronized keyword to allow only one thread at a time to access
critical sections.

Synchronized Method
class Counter {
private int count = 0;

public synchronized void increment() { // only one thread at a time


count++;
[Link]([Link]().getName() + " Count: " +
count);
}
}

public class SyncDemo {


public static void main(String[] args) {
Counter counter = new Counter();

Runnable r = () -> {
for(int i=0; i<5; i++) [Link]();
};

Thread t1 = new Thread(r, "Thread-1");


Thread t2 = new Thread(r, "Thread-2");
[Link]();
[Link]();
}
}

🔹 2. Inter-thread Communication
 Threads can communicate using wait(), notify(), and notifyAll().
 Commonly used in producer-consumer problem.

Example: Producer-Consumer
class SharedResource {
private int data;
private boolean available = false;

public synchronized void produce(int value) throws InterruptedException {


while (available) wait();
data = value;
[Link]("Produced: " + data);
available = true;
notify(); // wake up consumer
}

public synchronized void consume() throws InterruptedException {


while (!available) wait();
[Link]("Consumed: " + data);
available = false;
notify(); // wake up producer
}
}

🔹 3. Thread Groups
 ThreadGroup allows grouping threads for collective management.
 Can set priority, interrupt, or enumerate threads in a group.

Example
public class ThreadGroupDemo {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("MyGroup");

Thread t1 = new Thread(group, () -> [Link]("Thread 1


running"));
Thread t2 = new Thread(group, () -> [Link]("Thread 2
running"));

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

[Link]("Active threads in group: " +


[Link]());
}
}

🔹 4. Daemon Threads
 Daemon threads run in the background and terminate automatically when all user
threads finish.
 Useful for background tasks like garbage collection, monitoring.

Example
class DaemonDemo extends Thread {
public void run() {
while(true) {
[Link]([Link]().getName() + "
running");
try { [Link](1000); } catch (InterruptedException e) {}
}
}
}

public class Main {


public static void main(String[] args) {
DaemonDemo t = new DaemonDemo();
[Link](true); // set as daemon thread
[Link]();

[Link]("Main thread ends, daemon thread will terminate


automatically");
}
}

Key Points

Concept Description
Synchronization Prevents concurrent access to shared resources ( synchronized)
Inter-thread Communication wait(), notify(), notifyAll() for coordination
Thread Groups Groups threads for collective operations
Daemon Threads Background threads that terminate when all user threads finish

. Enumerations (enum)
 Enumeration defines a fixed set of constants.
 Introduced in Java 5, replaces int constants for better type safety.

Example
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class EnumDemo {


public static void main(String[] args) {
Day today = [Link];
[Link]("Today is: " + today);

// Iterate over enum


for (Day d : [Link]()) {
[Link](d);
}
}
}

 Methods in Enum: values(), valueOf(String name), ordinal().

🔹 2. Autoboxing and Unboxing


 Autoboxing: Automatic conversion of primitive types → wrapper objects.
 Unboxing: Automatic conversion of wrapper objects → primitive types.

Example
public class AutoBoxingDemo {
public static void main(String[] args) {
int a = 10;
Integer obj = a; // Autoboxing
[Link]("Integer object: " + obj);

int b = obj; // Unboxing


[Link]("Primitive int: " + b);
}
}

 Wrapper classes: Integer, Double, Float, Character, Boolean, Long, Short,


Byte.

🔹 3. Annotations
 Annotation = metadata that provides information about the code.
 Commonly used for compile-time checks, documentation, runtime processing.

Built-in Annotations

Annotation Purpose
@Override Indicates method overrides a superclass method
@Deprecated Marks method/class as deprecated
@SuppressWarnings Suppresses compiler warnings

Example
class Parent {
void show() { [Link]("Parent show"); }
}

class Child extends Parent {


@Override
void show() { [Link]("Child show"); }

@Deprecated
void oldMethod() { [Link]("Old method"); }
}

public class AnnotationDemo {


public static void main(String[] args) {
Child c = new Child();
[Link]();
[Link](); // Compiler warning: deprecated
}
}

 Can also define custom annotations with @interface.

🔹 4. Generics
 Generics allow type-safe code by specifying type parameters.
 Introduced in Java 5, mainly used in collections.

Example with Collections


import [Link].*;

public class GenericsDemo {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Java");
[Link]("Python");
// [Link](100); // ❌ Compile-time error

for(String lang : list) {


[Link](lang);
}
}
}

Generic Class
class Box<T> {
private T value;
void set(T value) { [Link] = value; }
T get() { return value; }
}

public class Main {


public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
[Link](10);
[Link]("Box contains: " + [Link]());
}
}

 T → type parameter; can also use E (element), K (key), V (value).

Key Points

Feature Key Points


Enumeration Defines fixed set of constants; type-safe; methods: values(), ordinal()
Autoboxing Automatic primitive → wrapper conversion
Unboxing Automatic wrapper → primitive conversion
Metadata for code; built-in: @Override, @Deprecated, @SuppressWarnings;
Annotations
custom possible
Generics Type-safe classes/methods; works with collections and custom classes

You might also like