Sybsc It - Core Java - Unit III
Sybsc It - Core Java - Unit III
Sybsc It - Core Java - Unit III
Exceptions :
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.
In Java, an 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. 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;
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited
by two subclasses: Exception and Error. The hierarchy of Java Exception classes is
given below:
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
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
Java provides five keywords that are used to handle the exception. The following table
describes each.
Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
JavaExceptionExample.java
There are given some scenarios where unchecked exceptions may occur. They are as
follows:
1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.
Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception (
i.e., Exception) or the generated exception type. However, the good approach is to
declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Example 1
TryCatchExample1.java
As displayed in the above example, the rest of the code is not executed (in such case,
the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled,
all the code below the exception won't be executed.
Let's see the solution of the above problem by a java try-catch block.
Example 2
TryCatchExample2.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Java Catch Multiple Exceptions
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.
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
Output :
Arithmetic Exception occurs
rest of the code
Java finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.
Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any).
ADVERTISEMENT
ADVERTISEMENT
o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.
Usage of Java finally
Let's see the different cases where Java finally block can be used.
Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.
TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:
Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the
catch block cannot handle it. Despite this, the finally block is executed after the try
block and then the program terminates abnormally.
TestFinallyBlock1.java
Output:
Example:
Let's see the following example where the Java code throws an exception and the
catch block handles the exception. Later the finally block is executed after the try-
catch block. Further, the rest of the code is also executed normally.
TestFinallyBlock2.java
Output:
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if the program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).
Java throw Exception
In Java, exceptions allows us to write good quality codes where the errors are checked
at the compile time instead of runtime and we can create custom exceptions making
the code recovery and debugging easier.
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related
to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It
is mainly used to throw a custom exception. We will discuss custom exceptions later
in this section.
We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a
number by another number. Here, we just need to set the condition and throw
exception using throw keyword.
In this example, we have created a method named validate() that accepts an integer
as a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.
ADVERTISEMENT
TestThrow1.java
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.
Output:
The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
TestThrow2.java
1. import java.io.*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {
7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");
9. BufferedReader fileInput = new BufferedReader(file);
10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. e.printStackTrace();
24. }
25. System.out.println("rest of the code...");
26. }
27. }
Output:
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.
TestThrow3.java
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 checking the code before it being used.
ADVERTISEMENT
ADVERTISEMENT
Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.
Testthrows1.java
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught
or declare the exception.
1. Case 1: We have caught the exception i.e. we have handled the exception using
try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the
method.
In case we handle the exception, the code will be executed fine whether exception
occurs during the program or not.
ADVERTISEMENT
ADVERTISEMENT
Testthrows2.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:
exception handled
normal flow...
Case 2: Declare Exception
o In case we declare the exception, if exception does not occur, the code will be
executed fine.
o In case we declare the exception and the exception occurs, it will be thrown at
runtime because throws does not handle the exception.
Testthrows3.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:
B) If exception occurs
ADVERTISEMENT
ADVERTISEMENT
Testthrows4.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:
The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
Difference between final, finally and finalize
The final, finally, and finalize are keywords in Java that are used in exception handling.
Each of these keywords has a different functionality. The basic difference between
final, finally and finalize is that the final is an access modifier, finally is the block in
Exception Handling and finalize is the method of object class.
Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
Multithreading :
1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
2) You can perform many operations together, so it saves time.
Multitasking
Threads are independent. If there occurs exception in one thread, it doesn't affect
other threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and
one process can have multiple threads.
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
New: Whenever a new thread is created, it is always in the new state. For a thread in
the new state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the
other is running.
o Runnable: A thread, that is ready to run is then moved to the runnable state.
In the runnable state, the thread may be running or may be ready to run at any
given instant of time. It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and
when that allocated time slice is over, the thread voluntarily gives up the CPU
to the other thread, so that the other threads can also run for their slice of time.
Whenever such a scenario occurs, all those threads that are willing to run,
waiting for their turn to run, lie in the runnable state. In the runnable state,
there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.
When the main thread invokes the join() method then, it is said that the main thread
is in the waiting state. The main thread then waits for the child threads to complete
their tasks. When the child threads complete their job, a notification is sent to the
main thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and
the chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread
(its name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the
time runs out, the thread wakes up and start its execution from when it has left earlier.
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.
Implementation of Thread States
In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent
the state of a thread. These constants are:
It represents the runnable state.It means a thread is waiting in the queue to run.
It represents the blocked state. In this state, the thread is waiting to acquire a lock.
It represents the waiting state. A thread will go to this state when it invokes the
Object.wait() method, or Thread.join() method with no timeout. A thread in the
waiting state is waiting for another thread to complete its task.
It represents the timed waiting state. The main difference between waiting and timed
waiting is the time constraint. Waiting has no time constraint, whereas timed waiting
has the time constraint. A thread invoking the following method reaches the timed
waiting state.
o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos
It represents the final state of a thread that is terminated or dead. A terminated thread
means it has completed its execution.
The following Java program shows some of the states of a thread defined above.
multiThread1.start();
multiThread1.sleep(2000);
multiThread2.start();multiThread2.sleep(4000);
multiThread3.start();
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
Output :
Running Thread Name: First Thread
Running Thread Priority: 1
Running Thread Name: Second Thread
Running Thread Priority: 10
Running Thread Name: Third Thread
Running Thread Priority: 5
Package :
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import
the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes
in net packages and so on.
Output:Hello subpackage
There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive. For example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:
Output:Welcome to package
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the
jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved
by the public class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}