Java Unit 3
Java Unit 3
Java Unit 3
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that
is why we need to handle exceptions. Let's consider a scenario
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5; //exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked
Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether
an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method signature.
Exception models :
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.
Termination Model
Resumptive Model
Termination Model
The Java exception handling facility supports the termination model. In the
termination model, when a method encounters an exception, further processing in
that method is terminated and control is transferred to the nearest exception handler
that can handle the type of exception encountered. It’s important to note that this
doesn’t necessarily mean the entire program is terminated. It depends on what
action the exception handler performs and where the exception handler is in the call
chain
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the
exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In resumptive model we hope to continue the execution after the exception
is handled.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.
The uncaught exceptions are the exceptions that are not caught by the compiler but
handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
Ex :
Exception handling :
Here's a list of different approaches to handle
exceptions in Java.
1. try...catch block
2. finally block
3. throw and throws keyword
try {
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException
division by zero " );
}
}
}
Output :
Arithmetic exception division by zero
Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch
for ArithmeticException must come before catch for Exception.
MultipleCatchBlock1.java
1. public class MultipleCatchBlock1 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Output:00:00/05:19
NestedTryBlock.java
1. public class NestedTryBlock{
2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }
Output:
.
Built-in exceptions :
Built-in exceptions are the exceptions which are available in
Java libraries. These exceptions are suitable to explain certain
error situations. Below is the list of important built-in
exceptions in Java.
Examples of Built-in Exception:
Example :
Output :
Custom Exception Occurred : This is a custom message
In process-based multitasking,
two or more processes and
programs can be run In thread-based multitasking, two or more
concurrently. threads can be run concurrently.
In process-based multitasking, a
process or a program is the In thread-based multitasking, a thread is
smallest unit. the smallest unit.
Here, it is unable to gain access It allows taking gain access over idle time
over the idle time of the CPU. taken by the CPU.
Process-Based Multitasking Thread-Based Multitasking
It is a comparatively
heavyweight. It is comparatively lightweight.
A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.
.
41.5M
814
o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:
2) Running
3) Suspended
4) Blocked
5) Terminated
A thread comes in this state when at any given time, it halts its execution
immediately.
Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or
by extending the Thread class. These are the only two ways through which we can
create a thread.
Let's dive into details of both these way of creating a thread:
Thread Class
A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class.
The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.
o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)
start() method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.
ThreadExample1.java
1. // Implementing runnable interface by extending Thread class
2. public class ThreadExample1 extends Thread {
3. // run() method to perform action for thread.
4. public void run()
5. {
6. int a= 10;
7. int b=12;
8. int result = a+b;
9. System.out.println("Thread started running..");
10. System.out.println("Sum of two numbers is: "+ result);
11. }
12. public static void main( String args[] )
13. {
14. // Creating instance of the class extend Thread class
15. ThreadExample1 t1 = new ThreadExample1();
16. //calling start method to execute the run() method of the Thread class
17. t1.start();
18. }
19. }
Output:
Output:
Main thread is- main
Thread-0, executing run() method!
49M
889
Java Try Catch
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
There are two types of synchronization Hello Java Program for Beginners
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive.
2. Cooperation (Inter-thread communication in java)
3. Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:
When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
Inter-thread Communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.
Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()