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

Java3 New

The document provides an overview of exception handling in Java, detailing key concepts such as exceptions, errors, and the exception hierarchy. It explains the use of keywords like try, catch, throw, throws, and finally, along with examples of checked and unchecked exceptions. Additionally, it covers the java.util package, including collection interfaces and classes, and concludes with a brief mention of multi-threading.

Uploaded by

jilikajithendar
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)
2 views22 pages

Java3 New

The document provides an overview of exception handling in Java, detailing key concepts such as exceptions, errors, and the exception hierarchy. It explains the use of keywords like try, catch, throw, throws, and finally, along with examples of checked and unchecked exceptions. Additionally, it covers the java.util package, including collection interfaces and classes, and concludes with a brief mention of multi-threading.

Uploaded by

jilikajithendar
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

Exception Handling in Java

Exception handling is a powerful mechanism that handles runtime errors, ensuring the normal flow
of the application is maintained. Java provides a robust exception-handling model to deal with
runtime errors and provides an easy way to create error-free, user-friendly applications.

Key Concepts in Exception Handling

1. Exception: An exception is an unwanted or unexpected event that disrupts the normal flow
of the program. These can be errors like invalid input, file not found, network issues, etc.

2. Error: Errors in Java represent serious issues that a program cannot recover from, such as
hardware failures or JVM errors. Examples are OutOfMemoryError, StackOverflowError.

3. Exception Hierarchy: In Java, exceptions are objects that are part of the Throwable class
hierarchy:

o Throwable (base class for all errors and exceptions)

▪ Error (e.g., OutOfMemoryError)

▪ Exception (for all exceptions)

▪ RuntimeException (unchecked exceptions, e.g.,


NullPointerException, ArrayIndexOutOfBoundsException)

▪ IOException, SQLException, etc. (checked exceptions)

Exception Handling Keywords in Java

1. try: The try block is used to wrap the code that may throw an exception. It defines a block of
code in which exceptions may occur.

2. catch: The catch block is used to handle exceptions. It is used immediately after the try block
and can handle specific types of exceptions.

3. throw: The throw keyword is used to manually throw an exception.

4. throws: The throws keyword is used in method signatures to indicate that a method may
throw exceptions. It tells the caller of the method that they should handle the exception.

5. finally: The finally block is always executed, whether or not an exception is thrown. It is
typically used for cleanup activities (e.g., closing file streams or database connections).

1. Types of Exceptions

1. Checked Exceptions (must be handled using try/catch or declared with throws)

2. Unchecked Exceptions (Runtime Exceptions) (occur at runtime, usually programming errors)

3. Errors (serious problems, not handled by programs)


2. Common Exception Classes in Java

Checked Exceptions

(these must be caught or declared)

• IOException

• FileNotFoundException

• SQLException

• ClassNotFoundException

• InterruptedException

• NoSuchMethodException

• NoSuchFieldException

Unchecked Exceptions (RuntimeException and its subclasses)

• ArithmeticException → divide by zero

• NullPointerException → using null object reference

• ArrayIndexOutOfBoundsException → invalid array index

• StringIndexOutOfBoundsException → invalid string index

• NumberFormatException → invalid number conversion

• IllegalArgumentException

• IllegalStateException

• ClassCastException → wrong type casting

Errors (not meant to be handled in code)

• StackOverflowError → infinite recursion

• OutOfMemoryError → heap memory full

• VirtualMachineError

• AssertionError

Using Try, Catch, Throw, Throws, and Finally

1. Basic Try and Catch


In this example, if a divideByZero method is called with a zero divisor, it will throw an exception
which is caught by the catch block.

public class Example {


public static void main(String[] args) {
try {
int result = divideByZero(10, 0); // This will throw an exception
[Link](result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("This block always runs");
}
}

public static int divideByZero(int a, int b) {


return a / b; // ArithmeticException will be thrown if b is zero
}
}
Output:

Error: / by zero

This block always runs

2. Using throw to Manually Throw Exceptions

You can manually throw exceptions using the throw keyword. Here's how you can create your own
custom exception:

class InvalidAgeException extends Exception {


public InvalidAgeException(String message) {
super(message);
}
}

public class Example {


public static void main(String[] args) {
try {
validateAge(15); // This will throw an InvalidAgeException
} catch (InvalidAgeException e) {
[Link]([Link]());
}
}

public static void validateAge(int age) throws InvalidAgeException {


if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
} else {
[Link]("Age is valid.");
}
}
}
Output:

Age must be 18 or older.

3. Using throws in Method Signatures

You can use the throws keyword in method signatures to declare that a method can throw one or
more exceptions.

import [Link].*;

public class Example {


public static void main(String[] args) {
try {
readFile("[Link]");
} catch (IOException e) {
[Link]("File not found: " + [Link]());
}
}

public static void readFile(String fileName) throws IOException {


FileReader file = new FileReader(fileName); // This may throw IOException
BufferedReader fileInput = new BufferedReader(file);
throw new IOException("Simulated IO Exception");
}
}
Output:

File not found: [Link]

4. Finally Block

The finally block always runs, regardless of whether an exception occurs or not. It is used for cleanup
operations, like closing resources.

public class Example {


public static void main(String[] args) {
try {
int result = 10 / 2;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Finally block always executes");
}
}
}
Output:

Result: 5

Finally block always executes

Built-in Exceptions in Java

Java provides a rich set of built-in exceptions for common scenarios.

• ArithmeticException: Thrown when an exceptional arithmetic condition occurs, e.g., dividing


by zero.

• NullPointerException: Thrown when the JVM attempts to access a member of an object that
is null.

• ArrayIndexOutOfBoundsException: Thrown when trying to access an array with an invalid


index.

• FileNotFoundException: Thrown when a file with the specified pathname does not exist.

• IOException: Thrown for general I/O errors, like issues while reading from or writing to files.

• ClassNotFoundException: Thrown when a class cannot be found.

Creating Custom Exception Subclasses

To create your own exception classes, you can extend the Exception class (or RuntimeException for
unchecked exceptions).

Example: Creating a Custom Exception Class

class InvalidEmailException extends Exception {


public InvalidEmailException(String message) {
super(message);
}
}

public class Example {


public static void main(String[] args) {
try {
String email = "invalid-email";
validateEmail(email);
} catch (InvalidEmailException e) {
[Link]([Link]());
}
}

public static void validateEmail(String email) throws InvalidEmailException {


if (![Link]("@")) {
throw new InvalidEmailException("Invalid email format: " + email);
} else {
[Link]("Email is valid.");
}
}
}
Output:

Invalid email format: invalid-email

Summary of Keywords and Usage

• try: Used to wrap code that may throw an exception.

• catch: Used to handle specific exceptions thrown by the try block.

• throw: Used to manually throw exceptions.

• throws: Used to declare that a method can throw exceptions.

• finally: A block that always runs, regardless of whether an exception occurred, typically used
for cleanup.

Conclusion

• Exception Handling in Java allows programs to handle runtime errors effectively and
prevents the program from terminating abruptly.

• Custom Exceptions can be created to handle specific cases, and Java provides a robust set of
built-in exceptions for various error scenarios.

3. [Link] Package (Important for Data Structures)

Collection Interface

• Root interface of Collection hierarchy.

• Defines common methods like add(), remove(), size(), iterator().

Collection<String> items = new ArrayList<>();


[Link]("Java");

List Interface

• Ordered, allows duplicates.

• Access elements by index.

• Implementations: ArrayList, LinkedList, Vector.

List<String> list = new ArrayList<>();


[Link]("Apple");
[Link]("Banana");
Queue Interface

• Used for FIFO (First In First Out) operations.

• Implementations: LinkedList, PriorityQueue.

Queue<String> queue = new LinkedList<>();


[Link]("Task1");
[Link]("Task2");
[Link]([Link]()); // Task1

4. Important Classes in [Link]

LinkedList Class

• Implements both List and Deque.

• Good for insertion/deletion.

LinkedList<String> ll = new LinkedList<>();


[Link]("Node1");
[Link]("Node0");
[Link]("Node2");

HashSet Class

• Implements Set, unordered, no duplicates.

• Fast for search operations.

HashSet<Integer> hs = new HashSet<>();


[Link](10);
[Link](20);
[Link](10); // Duplicate ignored

TreeSet Class

• Implements SortedSet, stores in ascending order.

• No duplicates, uses Red-Black Tree internally.

TreeSet<String> ts = new TreeSet<>();


[Link]("C");
[Link]("A");
[Link]("B"); // Output: A, B, C
StringTokenizer Class

• Breaks string into tokens/words.

StringTokenizer st = new StringTokenizer("Java is fun");


while([Link]()) {
[Link]([Link]());
}

Date Class

• Represents date and time.

Date d = new Date();


[Link](d); // Current system date and time

Random Class

• Generates random numbers.

Random rand = new Random();


[Link]([Link](100)); // 0 to 99

Scanner Class

• Used to read input from user or file.

Scanner sc = new Scanner([Link]);


[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello " + name);

Short Note for Revision:

Interface/Class Use

Collection Base interface for all collections

List Ordered, indexed, allows duplicates

Queue FIFO, task management

LinkedList Doubly linked list, fast insertion

HashSet Unique, unordered

TreeSet Unique, sorted


StringTokenizer Split strings into words

Date Time and date

Random Random number generation

Scanner Input reader

1. The Collection Interface

• The root interface of the Collections Framework.

• It represents a group of objects (called elements).

• Extended by List, Set, and Queue.

add(E e) → add an element


addAll(Collection c) → add all elements from another collection
remove(Object o) → remove element
clear() → remove all elements
contains(Object o) → check if element exists
size() → number of elements
isEmpty() → check empty
iterator() →

import [Link].*;

public class CollectionExample {


public static void main(String[] args) {
Collection<String> coll = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

for (String s : coll) {


[Link](s);
}
}
}

2. List Interface

• An ordered collection (sequence).

• Allows duplicate elements.

• Implementations: ArrayList, LinkedList, Vector.


import [Link].*;

public class ListExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("A"); // duplicates allowed

[Link](list); // [A, B, A]
}
}

3. Queue Interface

• Designed for holding elements prior to processing.

• Typically follows FIFO (First In, First Out).

• Implementations: LinkedList, PriorityQueue.


import [Link].*;

public class Main {


public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
[Link](10);
[Link](20);
[Link](30);

[Link]("Queue: " + q);


[Link]("Peek: " + [Link]());
[Link]("Poll: " + [Link]());
[Link]("After poll: " + q);
}
}

4. LinkedList Class

• Implements both List and Queue.

• Doubly linked list structure.

import [Link].*;

public class Main {


public static void main(String[] args) {
LinkedList<String> ll = new LinkedList<>();
[Link]("One");
[Link]("Two");
[Link]("Three");

[Link]("Zero");
[Link]("Four");

[Link]("LinkedList: " + ll);


[Link]();
[Link]();
[Link]("After remove: " + ll);
}
}

5. HashSet Class

• Implements Set interface.

• Stores unique elements (no duplicates).

• No guaranteed order.
import [Link].*;

public class HashSetExample {


public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
[Link](10);
[Link](20);
[Link](10); // duplicate ignored

[Link](set); // [20, 10] (order may vary)


}
}

6. TreeSet Class

• Implements Set.

• Stores elements in sorted order.

• No duplicates allowed.

import [Link].*;

public class Main {


public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<>();
[Link](50);
[Link](20);
[Link](10);
[Link](40);

[Link]("TreeSet (sorted): " + ts);


[Link]("First: " + [Link]());
[Link]("Last: " + [Link]());
}
}
7. StringTokenizer

• Used to split strings into tokens (like words).

• Works like a primitive tokenizer.

import [Link].*;

public class StringTokenizerExample {


public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Java is fun", " ");
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:

Java
is
fun

8. Date Class

• Represents a specific instant in time.

import [Link].*;

public class DateExample {


public static void main(String[] args) {
Date d = new Date();
[Link]("Current Date & Time: " + d);
}
}

9. Random Class

• Used to generate random numbers.

import [Link].*;

public class RandomExample {


public static void main(String[] args) {
Random r = new Random();
[Link]("Random int: " + [Link](100)); // 0–99
[Link]("Random double: " + [Link]());
}
}
10. Scanner Class

• Used to take input from keyboard ([Link]) or other sources.

import [Link].*;

public class ScannerExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
String name = [Link]();

[Link]("Enter age: ");


int age = [Link]();

[Link]("Hello " + name + ", Age: " + age);


}
}

Summary

• Collection → Root interface

• List → Ordered, allows duplicates (ArrayList, LinkedList)

• Queue → FIFO (LinkedList, PriorityQueue)

• HashSet → Unique elements, no order

• TreeSet → Unique, sorted elements

• StringTokenizer → Splits strings

• Date → Current date/time

• Random → Random values

• Scanner → User input

Multi threading
class mythread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Thread " + [Link]().getName() + " is running: " + i);
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
}
}
}

class mythread2 extends Thread {


@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Thread " + [Link]().getName() + " is running: " + i);
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
}
}
}

class multithreading {

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


mythread thread1 = new mythread();
mythread2 thread2 = new mythread2();

[Link]("Thread-1");
[Link]("Thread-2");

[Link]();
[Link]();
[Link](); // Wait for thread1 to finish
[Link](); // Wait for thread2 to finish
[Link]("All threads have finished execution.");
}
}
We will perform synchronization on method and block but nit for the predefined functions, variables
, classes we can peform on userdefined methods or a block of code

You might also like