Java Package_21_11_2023_Lecture Note
Java Package_21_11_2023_Lecture Note
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class
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
Simple example of java package
The package keyword is used to create a package in java.
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:
2
1. javac -d directory javafilename
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.
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.
3
Example of package that import the packagename.*
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
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
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
5
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
Package inside the package is called the subpackage. It should be created to categorize
the package further.
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.
6
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
7
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 cla
file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
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
There are two ways to load the class files temporary and permanent.
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
8
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.
If you want to put two public classes in a package, have two java source files containing one public
class, but keep the package name same. For example:
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{}
9
Access Modifiers in Java
1. Private access modifier
2. Role of private constructor
3. Default access modifier
4. Protected access modifier
5. Public access modifier
6. Access Modifier with Method Overriding
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.
10
Access within within outside package by subclass outside
Modifier class package only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
11
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
12
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only
through inheritance.
13
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
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.
3. package mypack;
4. import pack.*;
5.
14
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The default modifier is more restrictive than protected. That is why, there is a compile-
time error.
15
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit,
for example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You
can write the logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it
is easy and fast to create an encapsulated class in Java.
16
File: Student.java
File: Test.java
Output:
17
vijay
Read-Only class
Now, you can't change the value of the college data member which is "AKG".
Write-Only class
Now, you can't get the value of the college, you can only change the value of college data
member.
18
3. //So, it can't be accessed from outside the class
File: Account.java
19
28. return amount;
29. }
30. public void setAmount(float amount) {
31. this.amount = amount;
32. }
33.
34. }
File: TestAccount.java
Output:
20
Exception Handling in Java
1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur
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;
21
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement
5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be
executed. That is why we use exception handling in Java.
Do You Know?
o What is the difference between checked and unchecked exceptions?
o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?
22
Types of Java Exceptions
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
23
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
24
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.
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.
JavaExceptionExample.java
25
10. }
Output:
1. int a=50/0;//ArithmeticException
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
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
26
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there
may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
27
Java try-catch block
Java try block
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.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw an exception
3. }finally{}
The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
28
Internal Working of Java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
29
Example 1
TryCatchExample1.java
Output:
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.
30
Example 2
TryCatchExample2.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
31
Example 3
In this example, we also kept the code in a try block that will not throw an exception.
TryCatchExample3.java
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code
will not execute.
32
Example 4
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
33
Example 5
Let's see an example to print a custom message on exception.
TryCatchExample5.java
Output:
34
Example 6
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java
Output:
25
35
Example 7
In this example, along with try block, we also enclose exception code in a catch block.
TryCatchExample7.java
Output:
Here, we can see that the catch block didn't contain the exception code. So, enclose
exception code within a try block and use catch block only to handle the exceptions.
36
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a different
type of exception class (ArrayIndexOutOfBoundsException).
TryCatchExample8.java
Output:
37
Example 9
Let's see an example to handle another unchecked exception.
TryCatchExample9.java
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
38
Example 10
Let's see an example to handle checked exception.
TryCatchExample10.java
1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }
Output:
39
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.
40
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
Output:
41
Example 2
MultipleCatchBlock2.java
Output:
In this example, try block contains two exceptions. But at a time only one exception occurs
and its corresponding catch block is executed.
42
MultipleCatchBlock3.java
Output:
43
Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding
exception type. In such case, the catch block containing the parent exception
class Exception will invoked.
MultipleCatchBlock4.java
Output:
44
Example 5
Let's see an example, to handle the exception without maintaining the order of exceptions
(i.e. from most specific to most general).
MultipleCatchBlock5.java
1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Output:
Compile-time error
45
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
46
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
NestedTryBlock.java
47
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:
48
When any try block does not have a catch block for a particular exception, then the catch
block of the outer (parent) try block are checked for that exception, and if it matches, the
catch block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then
the Java runtime system will handle the exception. Then it displays the system generated
message for that exception.
Example 2
Let's consider the following example. Here the try block within nested try block (inner try
block 2) do not handle the exception. The control is then transferred to its parent try block
(inner try block 1). If it does not handle the exception, then the control is transferred to
the main try block (outer try block) where the appropriate catch block handles the
exception. It is termed as nesting.
NestedTryBlock.java
49
20. catch (ArithmeticException e) {
21. System.out.println("Arithmetic exception");
22. System.out.println(" inner try block 2");
23. }
24. }
25.
26. // to handle ArithmeticException
27. catch (ArithmeticException e) {
28. System.out.println("Arithmetic exception");
29. System.out.println("inner try block 1");
30. }
31. }
32.
33. // to handle ArrayIndexOutOfBoundsException
34. catch (ArrayIndexOutOfBoundsException e4) {
35. System.out.print(e4);
36. System.out.println(" outer (main) try block");
37. }
38. catch (Exception e5) {
39. System.out.print("Exception");
40. System.out.println(" handled in main try-block");
41. }
42. }
43. }
Output:
50
Java finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
Note: If you don't handle the exception, before terminating the program, JVM executes finally
block (if any).
51
Why use Java finally block?
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.
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. }
52
Output:
TestFinallyBlock1.java
53
20. System.out.println("finally block is always executed");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }
Output:
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
54
12.
13. //handles the Arithmetic Exception / Divide by zero exception
14. catch(ArithmeticException e){
15. System.out.println("Exception handled");
16. System.out.println(e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {
21. System.out.println("finally block is always executed");
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }
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).
55
Java throw keyword
The Java throw keyword is used to throw an exception explicitly.
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 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.
Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend
the Exception class.
56
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.
57
Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the exception
using catch block or the method must declare it using throws declaration.
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. }
58
25. System.out.println("rest of the code...");
26. }
27. }
Output:
TestThrow3.java
59
19. }
20. catch (UserDefinedException ude)
21. {
22. System.out.println("Caught the exception");
23. // Print the message from MyException object
24. System.out.println(ude.getMessage());
25. }
26. }
27. }
Output:
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
60
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Output:
exception handled
normal flow...
In the above example exception occurs in the m() method where it is not handled, so it is
propagated to the previous n() method where it is not handled, again it is propagated to
the p() method where exception is handled.
Exception can be handled in any method in call stack either in the main() method, p()
method, n() method or m() method.
61
Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).
1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
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.
62
Syntax of Java throws
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();
63
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.
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{
64
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...
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.
65
12. System.out.println("normal flow...");
13. }
14. }
Output:
B) If exception occurs
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:
66
Difference between throw and throws
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
67
5. Internal implementation We are allowed to throw only We can declare multiple
one exception at a time i.e. exceptions using throws
we cannot throw multiple keyword that can be thrown
exceptions. by the method. For example,
main() throws IOException,
SQLException.
Output:
68
Java throws Example
TestThrows.java
Output:
69
Java throw and throws Example
TestThrowAndThrows.java
Output:
70
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:
1. Definition final is the keyword and finally is the block in Java finalize is the method in
access modifier which is Exception Handling to Java which is used to
used to apply execute the important perform clean up
restrictions on a class, code whether the processing just before
method or variable. exception occurs or not. object is garbage
collected.
2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in exception
handling.
3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs
variable becomes important code even if the cleaning activities with
constant and cannot be exception occurs or not. respect to the object
modified. (2) finally block cleans up before its destruction.
(2) final method cannot all the resources used in
be overridden by sub try block
class.
(3) final class cannot be
inherited.
71
It's execution is not
dependant on the
exception.
FinalExampleTest.java
Output:
72
In the above example, we have declared a variable final. Similarly, we can declare the
methods and classes final using the final keyword.
FinallyExample.java
Output:
73
Java finalize Example
FinalizeExample.java
Output:
74
Exception Handling with Method Overriding in
Java
There are many rules if we talk about method overriding with exception handling.
TestExceptionChild.java
1. import java.io.*;
2. class Parent{
3.
4. // defining the method
5. void msg() {
6. System.out.println("parent method");
7. }
8. }
9.
10. public class TestExceptionChild extends Parent{
11.
75
12. // overriding the method in child class
13. // gives compile time error
14. void msg() throws IOException {
15. System.out.println("TestExceptionChild");
16. }
17.
18. public static void main(String args[]) {
19. Parent p = new TestExceptionChild();
20. p.msg();
21. }
22. }
Output:
Rule 2: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
TestExceptionChild1.java
1. import java.io.*;
2. class Parent{
3. void msg() {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild1 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
76
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild1();
15. p.msg();
16. }
17. }
Output:
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild2 extends Parent{
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
77
14. Parent p = new TestExceptionChild2();
15.
16. try {
17. p.msg();
18. }
19. catch (Exception e){}
20.
21. }
22. }
Output:
1. import java.io.*;
2. class Parent{
3. void msg() throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild3 extends Parent {
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
78
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild3();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }
Output:
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild4 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild4();
79
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }
Output:
1. import java.io.*;
2. class Parent {
3. void msg()throws Exception{
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild5 extends Parent{
9. void msg() {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild5();
15.
16. try {
80
17. p.msg();
18. }
19. catch(Exception e) {}
20.
21. }
22. }
Output:
81
TestExceptionChild.java
1. import java.io.*;
2. class Parent{
3.
4. // defining the method
5. void msg() {
6. System.out.println("parent method");
7. }
8. }
9.
10. public class TestExceptionChild extends Parent{
11.
12. // overriding the method in child class
13. // gives compile time error
14. void msg() throws IOException {
15. System.out.println("TestExceptionChild");
16. }
17.
18. public static void main(String args[]) {
19. Parent p = new TestExceptionChild();
20. p.msg();
21. }
22. }
Output:
Rule 2: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
82
TestExceptionChild1.java
1. import java.io.*;
2. class Parent{
3. void msg() {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild1 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild1();
15. p.msg();
16. }
17. }
Output:
1. import java.io.*;
83
2. class Parent{
3. void msg()throws ArithmeticException {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild2 extends Parent{
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild2();
15.
16. try {
17. p.msg();
18. }
19. catch (Exception e){}
20.
21. }
22. }
Output:
84
Example in case subclass overridden method declares same
exception
TestExceptionChild3.java
1. import java.io.*;
2. class Parent{
3. void msg() throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild3 extends Parent {
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild3();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }
Output:
85
Example in case subclass overridden method declares subclass
exception
TestExceptionChild4.java
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild4 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild4();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }
Output:
86
Example in case subclass overridden method declares no
exception
TestExceptionChild5.java
1. import java.io.*;
2. class Parent {
3. void msg()throws Exception{
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild5 extends Parent{
9. void msg() {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild5();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20.
21. }
22. }
Output:
87
Java Custom Exception
In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user
need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we
have passed a string to the constructor of superclass i.e. Exception class that can be
obtained using getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java
programs.
In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
88
Note: We need to write the constructor that takes the String as the error message and it is
called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor
of InvalidAgeException takes a string as an argument. This string is passed to constructor
of parent class Exception using the super() method. Also the constructor of Exception class
can be called without using a parameter and calling super() method is not mandatory.
TestCustomException1.java
89
25. }
26.
27. // main method
28. public static void main(String args[])
29. {
30. try
31. {
32. // calling the method
33. validate(13);
34. }
35. catch (InvalidAgeException ex)
36. {
37. System.out.println("Caught the exception");
38.
39. // printing the message from InvalidAgeException object
40. System.out.println("Exception occured: " + ex);
41. }
42.
43. System.out.println("rest of the code...");
44. }
45. }
Output:
Example 2:
TestCustomException2.java
90
8. public class TestCustomException2
9. {
10. // main method
11. public static void main(String args[])
12. {
13. try
14. {
15. // throw an object of user defined exception
16. throw new MyCustomException();
17. }
18. catch (MyCustomException ex)
19. {
20. System.out.println("Caught the exception");
21. System.out.println(ex.getMessage());
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }
Output:
91