Unit - III Exception Handling and Multithreading

 Unit - III Exception Handling and Multithreading 

3.1 Errors and Exception: Types of errors and exceptions, try and catch statement, throws and finally statement, built-in exceptions, throwing our own exception

 3.2 Multithreaded programming : creating a thread: By extending to thread class and by implementing runnable Interface, Life cycle of thread: Thread methods, thread exceptions, thread priority and methods, synchronization


3.1 Errors and Exception: Types of errors and exceptions, try and catch statement, throws and finally statement, built-in exceptions, throwing our own exception

Errors and Exceptions in Java

  • Errors and exceptions are problems that arise during program execution and disrupt the normal flow of a program.

  • Errors are serious issues related to the system (e.g., OutOfMemoryError, StackOverflowError) and cannot be handled by the program.

  • Exceptions are events that can be handled using exception handling mechanisms like try-catch.

  • Java exceptions are categorized into checked (compile-time) and unchecked (runtime) exceptions.

  • Proper exception handling improves program stability and user experience by gracefully handling unexpected situations.

  • Common exception classes include ArithmeticException, NullPointerException, IOException, etc.


try and catch Statement

Used to catch and handle exceptions gracefully without terminating the program.

Syntax:

try { // code that may throw exception } catch (ExceptionType e) { // handling code }

Example:

class Demo { public static void main(String[] args) { try { int a = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } } }

throws Statement

Used to declare an exception that might be thrown by a method.

Syntax:

return_type method_name() throws ExceptionType { // code }

Example:

class Demo { static void test() throws ArithmeticException { int a = 10 / 0; } public static void main(String[] args) { try { test(); } catch (ArithmeticException e) { System.out.println("Exception handled"); } } }

finally Statement

Used to execute code regardless of whether an exception occurred or not.

Syntax:

try { // risky code } catch (ExceptionType e) { // handling } finally { // cleanup code }

Example:

class Demo { public static void main(String[] args) { try { int a = 5 / 0; } catch (ArithmeticException e) { System.out.println("Error handled"); } finally { System.out.println("Always executed"); } } }

Types of Errors in Java

  1. Syntax Errors

    • These occur when you break Java’s grammar rules.

    • Example: Missing semicolon, misspelled keyword.

    • Detected at compile time.

  2. Logical Errors

    • Program compiles and runs, but output is incorrect due to wrong logic.

    • Example: Using + instead of -.

    • Detected by testing the program.

  3. Runtime Errors

    • Errors that occur during program execution.

    • Example: Dividing by zero, accessing invalid array index.

    • Usually throw exceptions.


Types of Exceptions in Java

Java exceptions are divided into two main categories:

1. Checked Exceptions (Compile-time)

  • Must be either caught using try-catch or declared using throws.

  • Compiler checks them.

  • Example classes:

    • IOException

    • SQLException

    • FileNotFoundException

2. Unchecked Exceptions (Runtime)

  • Not checked by the compiler.

  • Occur due to programming mistakes.

  • Example classes:

    • ArithmeticException

    • NullPointerException

    • ArrayIndexOutOfBoundsException

    • NumberFormatException


Additional Classification:

TypeWhen Occurs          Examples
Compile-time Errors| During compilation          Syntax Errors, Missing files
Runtime Errors During program execution      ArithmeticException,NullPointerException
Logical Errors      Wrong program logic      Incorrect result despite no error

Built-in and User-defined Exceptions

  1. Java provides a rich set of built-in exception classes to handle common runtime errors like division by zero, null access, invalid input, etc.

  2. All exception classes are part of the java.lang package and inherit from the Throwable class.

  3. Common built-in exceptions include ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, and NumberFormatException.

  4. Java allows creating custom (user-defined) exceptions by extending the Exception class to handle application-specific error conditions.

  5. A user-defined exception can be thrown using the throw keyword and must be caught or declared using throws.

  6. This custom handling improves code clarity, debugging, and error tracking for specific business logic issues.


Built-in Exception Example

class Demo { public static void main(String[] args) { int a = 10, b = 0; try { int c = a / b; } catch (ArithmeticException e) { System.out.println("Built-in Exception: " + e); } } }

User-defined Exception (Throwing Own Exception)

Syntax:

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

Example:

class MyException extends Exception { MyException(String message) { super(message); } } class Test { static void checkAge(int age) throws MyException { if (age < 18) { throw new MyException("Age must be 18 or above"); } else { System.out.println("Valid age"); } } public static void main(String[] args) { try { checkAge(15); } catch (MyException e) { System.out.println("Custom Exception: " + e.getMessage()); } } }


Multithreaded Programming in Java

  1. Multithreading allows the execution of two or more threads simultaneously for better performance and resource utilization.

  2. A thread is a lightweight subprocess and can be created in Java by extending the Thread class or implementing the Runnable interface.

  3. Each thread has a life cycle that includes states: New, Runnable, Running, Blocked/Waiting, and Terminated.

  4. Java provides several thread control methods like start(), run(), sleep(), join(), yield(), etc., to manage thread execution.

  5. Threads can be assigned priorities using setPriority() method, and priorities can affect the thread scheduling.

  6. Synchronization is used to control access to shared resources to avoid race conditions and ensure thread safety.


Creating a Thread by Extending Thread Class


class MyThread extends Thread { public void run() { for (int i = 1; i <= 3; i++) { System.out.println("Thread running: " + i); } } public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } }

Creating a Thread by Implementing Runnable Interface


class MyRunnable implements Runnable { public void run() { for (int i = 1; i <= 3; i++) { System.out.println("Runnable thread: " + i); } } public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } }

Life Cycle of a Thread

  1. New – Thread is created using new keyword.

  2. Runnable – Thread is ready to run after start() is called.

  3. Running – Thread is currently executing.

  4. Waiting/Blocked – Thread is paused or waiting for a resource.

  5. Terminated – Thread finishes execution or is stopped.



Thread Methods

  • start() – Starts the thread

  • run() – Defines thread execution code

  • sleep(ms) – Pauses thread for specified milliseconds

  • join() – Waits for a thread to finish

  • yield() – Causes current thread to pause for other threads.


Thread Priority and Methods

  • setPriority(int value) – Sets thread priority from 1 to 10

  • getPriority() – Returns thread priority

  • Thread constants: Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, Thread.MAX_PRIORITY


Thread Synchronization

Used to prevent multiple threads from accessing the same resource simultaneously.

Syntax:

synchronized void methodName() { // synchronized code }

Example:

class Table { synchronized void printTable(int n) { for (int i = 1; i <= 5; i++) { System.out.println(n * i); } } } class MyThread extends Thread { Table t; MyThread(Table t) { this.t = t; } public void run() { t.printTable(5); } } class Demo { public static void main(String[] args) { Table obj = new Table(); MyThread t1 = new MyThread(obj); MyThread t2 = new MyThread(obj); t1.start(); t2.start(); } }

Comments

Popular posts from this blog

Syllabus

Unit VI: Interacting with Database

V. Java Networking