Notes Unit 5
Notes Unit 5
UNIT-5
EXCEPTION HANDLING AND MULTITHREADED PROGRAMMING
5.1 TYPES OF ERROR
1.Compile-time Errors:
Compile-time errors, also known as compilation errors or syntax errors, occur during the compilation
phase of the program.
These errors are caused by violations of the Java syntax rules or incorrect usage of language
constructs.
Examples of compile-time errors include missing semicolons, undefined variables, incompatible
types, or using a reserved keyword as an identifier.
When a compile-time error occurs, the compiler generates an error message, and the program cannot
be compiled until the errors are fixed.
2.Runtime Errors:
Runtime errors, also called exceptions, occur during the execution of the program.
These errors are caused by exceptional conditions or unexpected situations that arise while the
program is running.
Common examples of runtime errors include division by zero (ArithmeticException), accessing an
array element with an invalid index (ArrayIndexOutOfBoundsException), or attempting to open a
non-existent file (FileNotFoundException).
When a runtime error occurs, an exception object is thrown, which can be caught and handled using
exception handling mechanisms like try-catch blocks. If unhandled, the program terminates abruptly.
3.Logical Errors:
Logical errors, also known as semantic errors or bugs, occur when the program's logic or algorithm
is incorrect.
These errors do not cause the program to crash or generate error messages but result in undesired or
incorrect behavior.
Logical errors can be challenging to identify as they do not produce any compile-time or runtime
errors. The program runs successfully, but the output or behavior is not as expected.
Detecting and fixing logical errors typically involves careful code review, debugging, and testing.
It is important to note that compile-time errors are caught by the compiler during the compilation process,
runtime errors occur during program execution and can be caught and handled using exception handling,
while logical errors require careful analysis and debugging to identify and fix.
JAVA PROGRAMMING
1. Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception.
Checked Exception:
Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-
time by the compiler.
EXAMPLE:
import java.io.*;
class CheckedExceptionExample
{
JAVA PROGRAMMING
2. User-defined Exception
we can write our own exception class by extends the Exception class. We can throw our own exception on a
particular condition using the throw keyword. For creating a user-defined exception, we should have basic
knowledge of the try-catch block and throw keyword.
EXAMPLE:
import java.util.*;
class UserDefinedException
{
public static void main(String args[])
{
try{
throw new NewException(5);
}
catch(NewException ex)
{
System.out.println(ex);
}
}
}
class NewException extends Exception
{
int x;
NewException(int y)
{
x=y;
}
public String toString()
{
return ("Exception value = "+x) ;
}
}
JAVA PROGRAMMING
If an exception occurs within the try block, the control immediately transfers to the corresponding catch
block based on the type of exception.
Each catch block specifies the type of exception it can handle. If the caught exception matches the type
specified in a catch block, that catch block is executed.
If no catch block is found that matches the type of the thrown exception, the exception propagates to the
next level of the method call stack or terminates the program if it reaches the main method without being
caught.
EXAMPLE:
public class Main
{
public static void main(String[ ] args)
{
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
JAVA PROGRAMMING
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
JAVA PROGRAMMING
2.throws Keyword:
The throws keyword is used in a method declaration to indicate that the method may throw one or
more types of exceptions.
It specifies that the method is not handling the exception itself but is instead passing the
responsibility to the calling method or the JVM.
Multiple exceptions can be declared using a comma-separated list.
EXAMPLE:
import java.io.*;
class M{
void method()throws IOException
{
throw new IOException("device error");
}
}
public class Testthrows2
{
public static void main(String args[])
{
try{
M m=new M();
m.method();
}
catch(Exception e){System.out.println("exception handled");
}
System.out.println("normal flow...");
}
}
It's important to note that throw is used to raise an exception explicitly within a method, whereas throws is
used to indicate that a method may potentially throw an exception, allowing the caller to handle it or
propagate it further.
JAVA PROGRAMMING
1.New:
The thread is in the new state when it has been created but has not yet started.
In this state, the thread has been instantiated but has not yet invoked the start() method.
2.Runnable:
When the start() method is called, the thread enters the runnable state.
In this state, the thread is eligible for execution, but it may or may not be currently executing.
The thread scheduler selects a thread from the runnable pool and executes it.
3.Running:
A thread enters the running state when it starts executing its run() method.
In this state, the actual execution of the thread's code is taking place.
The thread remains in this state until it is paused, interrupted, or its execution completes.
JAVA PROGRAMMING
4.Blocked/Waiting:
A thread can transition to the blocked or waiting state for various reasons:
Blocked: If the thread is waiting for a monitor lock to enter a synchronized block or method and another
thread holds the lock.
Waiting: If the thread is waiting indefinitely for another thread to perform a particular action, such as
waiting for a condition to be satisfied or waiting for a notify/notifyAll signal.
5.Timed Waiting:
Similar to the blocked/waiting state, a thread can also enter a timed waiting state, where it waits for a
specific period of time.
This state is reached when the thread calls methods such as Thread.sleep(), Object.wait(), or Thread.join()
with a specified timeout.
6.Terminated:
A thread enters the terminated state when its run() method completes execution or when it is terminated
prematurely.
5.8 MULTITHREADING
Multithreading in Java refers to the concurrent execution of multiple threads within a single program. It
allows different threads to run independently, performing tasks simultaneously and improving overall
application performance and responsiveness. Java provides built-in features and APIs to support
multithreading, making it easier to develop concurrent applications.
EXAMPLE:
class MultithreadingDemo extends Thread
{
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
JAVA PROGRAMMING
}
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}