Java Unit 3 Notes
Java Unit 3 Notes
Java Unit 3 Notes
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
What is exception?
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions
are checked at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
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 catch block that can handle the
type of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to
get back to where the exception occurred.
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.
Uncaught Exception
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
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
known dispatchUncaughtException( ), on the Thread class in which the exception occurs
and terminates the thread.
Example:
import java.util.Scanner;
public class UncaughtExceptionExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}
Output:
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block
only. You can use multiple catch block with a single try.
}}
Output:
As displayed in the above example, rest of the code is not executed (in such case, rest
of the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will
not be executed.
int data=50/0;
}catch(ArithmeticException e)
{System.out.println(e);} System.out.println("rest of
the code...");
}}
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
Output:task1
completed rest
of the code...
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);} System.out.println("other statement);
}catch(Exception e)
{System.out.println("handeled");}
System.out.println("normal flow..");
}
1. }
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
Output:5
finally block is always executed
We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
1. throw exception;
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}}
Output:
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
2. //method code
3. }
4.
Let's see the example of java throws clause which describes that checked exceptions
can be propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception
handled");} }
obj.p();
System.out.println("normal flow..."); } }
Output:
exception handled
normal flow...
Java Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need.
By the help of custom exception, you can have your own exception and message.
super(s);
}}
class TestCustomException1{
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
}}
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
How to create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on
a thread.Thread class extends Object class and implements Runnable interface.
oThread()
o Thread(String name)
o Thread(Runnable r)
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
o When the thread gets a chance to execute, its target run() method will run.
Java Thread Example by extending Thread class
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}}
Output:thread is running...
}
public static void main(String args[]){
Output:thread is running...
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
class Customer{
int amount=10000;
if(this.amount<amount){
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
new Thread(){
public void run(){c.deposit(10000);}
}
start();
}}
withdraw completed
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we
can suspend, resume or interrupt group of threads by a single method call.
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is
the class that implements Runnable interface and "one", "two" and "three" are the thread
names.
Thread.currentThread().getThreadGroup().interrupt();
The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network
protocols −
Socket Programming − This is the most widely used concept in Networking and it
has been explained in very detail.
java.text
The java.text package is necessary for every java developer to master because it has a lot
of classes that is helpful in formatting such as dates, numbers, and messages.
java.text Classes
[table]
Class|Description
SimpleDateFormat|is a concrete class that helps in formatting and parsing of
dates. [/table]