0% found this document useful (0 votes)
7 views70 pages

Module 4

The document covers Object Oriented Programming in Java, focusing on packages and exceptions. It explains the Object class, its methods, and how to create and use packages, including built-in and user-defined packages, as well as access modifiers. Additionally, it provides examples of package usage, compilation, and running Java programs, along with details on access modifiers and their scopes.

Uploaded by

remogowda9343
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views70 pages

Module 4

The document covers Object Oriented Programming in Java, focusing on packages and exceptions. It explains the Object class, its methods, and how to create and use packages, including built-in and user-defined packages, as well as access modifiers. Additionally, it provides examples of package usage, compilation, and running Java programs, along with details on access modifiers and their scopes.

Uploaded by

remogowda9343
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming with JAVA(BCS306A) Module-4

PACKAGES AND EXCEPTIONS

Packages: Packages, Packages and Member Access, Importing Packages.


Exceptions: Exception-Handling Fundamentals, Exception Types, Uncaught Exceptions, Using try and catch,
Multiple catch Clauses, Nested try Statements, throw, throws, finally, Java’s Built-in Exceptions, Creating Your
Own Exception Subclasses, Chained Exceptions.
Object class in Java

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of
java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class
reference variable can refer the child class object, know as upcasting.

.IN
Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:
C
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be compared, object can be
N
cloned, object can be notified etc.
SY
U
VT

Methods of Object class

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 1


Object Oriented Programming with JAVA(BCS306A) Module-4

The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class object of this object. The Class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

.IN
protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object. C
public String toString() returns the string representation of this object.
N
public final void notify() wakes up single thread, waiting on this object's
monitor.
SY

public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
U

public final void wait(long timeout)throws causes the current thread to wait for the specified
VT

InterruptedException milliseconds, until another thread notifies (invokes


notify() or notifyAll() method).

public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is
being garbage collected.

Java Package

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 2


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link] Package

[Link] of package

[Link] package

1. By import packagename.*

2. By import [Link]

3. By fully qualified name

4. Subpackage

5. Sending class file to another directory

6. -classpath switch

.IN
7. 4 ways to load the class file or jar file

8. How to put two public class in a package


C
9. Static Import

10. Package class


N
A java package is a group of similar types of classes, interfaces and sub-packages.
SY

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.
U

Here, we will have the detailed learning of creating and using user-defined packages.
VT

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 3


Object Oriented Programming with JAVA(BCS306A) Module-4

.IN
C
Simple example of java package
N
The package keyword is used to create a package in java.
SY

//save as [Link]
U

package mypack;
VT

public class Simple

public static void main(String args[])

[Link]("Welcome to package");

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 4


Object Oriented Programming with JAVA(BCS306A) Module-4

1. javac -d directory javafilename

For example

1. javac -d . [Link]

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).

How to run java package program

You need to use fully qualified name e.g. [Link] etc to run the class.

To Compile: javac -d . [Link] .IN


C
To Run: java [Link]
N
Output:Welcome to package
SY

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.
U

How to access package from another package?


VT

There are three ways to access the package from outside the package.

1. import package.*;

2. import [Link];

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.

Example of package that import the packagename.*


//save by [Link]

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 5


Object Oriented Programming with JAVA(BCS306A) Module-4

package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;

.IN
class B
{
C
public static void main(String args[])
N
{
A obj = new A();
SY

[Link]();
}
U

}
Output:Hello
VT

2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
Example of package by import [Link]
//save by [Link]

package pack;
public class A
{
public void msg()
{

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 6


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();

.IN
[Link]();
}
C
}
N
Output:Hello
SY

3) Using fully qualified name


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.
U

It is generally used when two packages have same class name e.g. [Link] and [Link] packages contain Date class.
VT

Example of package by import fully qualified name


//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 7
Object Oriented Programming with JAVA(BCS306A) Module-4

package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Output:Hello

.IN
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.
C
N
Note: Sequence of the program must be package then import then class.
SY
U
VT

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

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 8


Object Oriented Programming with JAVA(BCS306A) Module-4

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.
The standard of defining package is [Link] e.g. [Link] or [Link].

Example of Subpackage

package [Link];
class Simple
{
public static void main(String args[])
{
[Link]("Hello subpackage");

.IN
}
}
To Compile: javac -d . [Link]
C
To Run: java [Link]
N
Output:Hello subpackage
SY

How to send the class file to another directory or drive?


U

There is a scenario, I want to put the class file of [Link] source file in classes folder of c: drive. For example:
VT

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 9


Object Oriented Programming with JAVA(BCS306A) Module-4

//save as [Link] .IN


C
package mypack;
N
public class Simple
SY

public static void main(String args[])


U

{
VT

[Link]("Welcome to package");

To Compile:

e:\sources> javac -d c:\classes [Link]

To Run:

To run this program from e:\source directory, you need to set classpath of the directory where the
class file resides.

e:\sources> set classpath=c:\classes;.;

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 10


Object Oriented Programming with JAVA(BCS306A) Module-4

e:\sources> java [Link]

Another way to run this program by -classpath switch of java:

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:

e:\sources> java -classpath c:\classes [Link]

Output:Welcome to package

Ways to load the class files or jar files


.IN
C
There are two ways to load the class files temporary and permanent.
N
o Temporary
SY

o By setting the classpath in the command prompt


o By -classpath switch
o Permanent
U

o By setting the classpath in the environment variables


VT

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.

//save as [Link] otherwise Compilte Time Error

class A
{
}
class B

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 11


Object Oriented Programming with JAVA(BCS306A) Module-4

{
}
public class C
{
}

How to put two public classes in a package?

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:

//save as [Link]

package javatpoint;
.IN
C
public class A
{
N
}
SY

//save as [Link]

package javatpoint;
U

public class B
VT

{
}

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.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 12


Object Oriented Programming with JAVA(BCS306A) Module-4

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.

There are four types of Java access modifiers:

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.

.IN
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.
C
Understanding Java Access Modifiers
N
Let's understand the access modifiers in Java by a simple table.
SY

Access within within outside package by outside


Modifier class package subclass only package
U

Private Y N N N
VT

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.

Simple example of private access modifier

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.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 13
Object Oriented Programming with JAVA(BCS306A) Module-4

class A

private int data=40;

private void msg()

[Link]("Hello java");

.IN
public class Simple

{
C
public static void main(String args[])
N
{

A obj=new A();
SY

[Link]([Link]);//Compile Time Error

[Link]();//Compile Time Error


U

}
VT

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:

class A

private A()

}//private constructor

void msg()

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 14


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]("Hello java");

public class Simple

public static void main(String args[])

A obj=new A();//Compile Time Error

.IN
}

}
C
Note: A class cannot be private or protected except nested class.
N
SY

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
U

package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more
VT

restrictive than protected, and public.

Example of default access modifier

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.

//save by [Link]

package pack;

class A

void msg()

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 15


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]("Hello");

}
//save by [Link]

package mypack;

import pack.*;

class B

.IN
public static void main(String args[])

{
C
A obj = new A();//Compile Time Error

[Link]();//Compile Time Error


N
}
SY

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
U

package.
VT

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.

It provides more accessibility than the default modifer.

Example of protected access modifier

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 16


Object Oriented Programming with JAVA(BCS306A) Module-4

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.

//save by [Link]

package pack;

public class A

protected void msg()

.IN
[Link]("Hello");

}
C
}
//save by [Link]
N
package mypack;
SY

import pack.*;
U

class B extends A
VT

public static void main(String args[])

B obj = new B();

[Link]();

}
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 17


Object Oriented Programming with JAVA(BCS306A) Module-4

Example of public access modifier

//save by [Link]

package pack;

public class A

public void msg()

[Link]("Hello");

.IN
}

}
C
//save by [Link]
N
package mypack;
SY

import pack.*;
U

class B
VT

public static void main(String args[])

A obj = new A();

[Link]();

}
Output:Hello

Java Access Modifiers with Method Overriding

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 18


Object Oriented Programming with JAVA(BCS306A) Module-4

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

class A
{
protected void msg()
{
[Link]("Hello java");
}
}
public class Simple extends A
{

.IN
void msg()
{
[Link]("Hello java"); //[Link]
C
}
N
public static void main(String args[])
{
SY

Simple obj=new Simple();


[Link]();
U

}
}
VT

The default modifier is more restrictive than protected. That is why, there is a compile-time error.

Exception Handling in Java

[Link] Handling
[Link] of Exception Handling
[Link] of Exception classes
[Link] of Exception
[Link] Example
[Link] 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.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 19


Object Oriented Programming with JAVA(BCS306A) Module-4

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at
runtime.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IO Exception, SQL
Exception, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An exception

.IN
normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a
scenario:
statement 1;
C
statement 2;
N
statement 3; ;//exception occurs
SY

statement 4;

statement 5
U

Suppose there are 5 statements in a Java program and an exception occurs at statement 3; the rest of the code will
VT

not be executed, i.e., statements 4 to 5 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.

Hierarchy of Java Exception classes

The [Link] 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:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 20


Object Oriented Programming with JAVA(BCS306A) Module-4

.IN
C
N
SY
U

Types of Java Exceptions


VT

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(unchecked Exception)

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 21


Object Oriented Programming with JAVA(BCS306A) Module-4

.IN
C
N
Difference between Checked and Unchecked Exceptions
SY

1) Checked Exception

The classes that directly inherit the Throwable class except Runtime Exception and Error are known as checked
exceptions.
U

For example,
VT

IO Exception,

SQL Exception, etc.

Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the Runtime Exception are known as unchecked exceptions.

For example,

Arithmetic Exception,

NullPointerException,

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 22


Object Oriented Programming with JAVA(BCS306A) Module-4

ArrayIndexOutOfBoundsException, etc.

Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable.

Some examples of errors are

OutOfMemoryError,

VirtualMachineError,

Assertion Error etc.

.IN
Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes each.
C
Keyword Description
N
SY

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.
U

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
VT

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.

Throw The "throw" keyword is used to throw an exception.

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.

Types of Exception in Java

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 23


Object Oriented Programming with JAVA(BCS306A) Module-4

In Java, exception is an event that occurs during the execution of a program and disrupts the normal flow of the
program's instructions. Bugs or errors that we don't want and restrict our program's normal execution of code are
referred to as exceptions. In this section, we will focus on the types of exceptions in Java and the differences
between the two.

Exceptions can be categorized into two ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions

.IN
C
N
SY
U
VT

Built-in Exception

Exceptions that are already available in Java libraries are referred to as built-in exception. These exceptions are
able to define the error situation so that we can understand the reason of getting this error. It can be categorized into
two broad categories, i.e., checked exceptions and unchecked exception.

Checked Exception

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 24


Object Oriented Programming with JAVA(BCS306A) Module-4

Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by
the compiler. The compiler ensures whether the programmer handles the exception or not. The programmer should
have to handle the exception; otherwise, the system has shown a compilation error.

[Link]

import [Link].*;

class CheckedExceptionExample

public static void main(String args[])

.IN
{

FileInputStream file_data = null;


C
file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/[Link]");
N
int m;
SY

while(( m = file_data.read() ) != -1)

[Link]((char)m);
U

}
VT

file_data.close();

In the above code, we are trying to read the [Link] file and display its data or content on the screen. The program
throws the following exceptions:

1. The FileInputStream(File filename) constructor throws the FileNotFoundException that is checked


exception.
2. The read() method of the FileInputStream class throws the IOException.
3. The close() method also throws the IOException.

Output:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 25


Object Oriented Programming with JAVA(BCS306A) Module-4

How to resolve the error?


.IN
C
There are basically two ways through which we can solve these errors.
N
1) The exceptions occur in the main method. We can get rid from these compilation errors by declaring the
SY

exception in the main method using the throws We only declare the IOException, not FileNotFoundException,
because of the child-parent relationship. The IOException class is the parent class of FileNotFoundException, so
this exception will automatically cover by IOException. We will declare the exception in the following way:
U

class Exception
VT

public static void main(String args[]) throws IOException

...

...

If we compile and run the code, the errors will disappear, and we will see the data of the file.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 26


Object Oriented Programming with JAVA(BCS306A) Module-4

2) We can also handle these exception using try-catch However, the way which we have used above is not correct.
We have to a give meaningful message for each exception type. By doing that it would be easy to understand the
error. We will use the try-catch block in the following way:

.IN
C
[Link]
N
import [Link].*;

class Exception
SY

public static void main(String args[])


U

{
VT

FileInputStream file_data = null;

try

file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/programs/[Link]"); }

catch(FileNotFoundException fnfe)

[Link]("File Not Found!");

int m;

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 27


Object Oriented Programming with JAVA(BCS306A) Module-4

try

while(( m = file_data.read() ) != -1)

[Link]((char)m);

file_data.close();

catch(IOException ioe)

.IN
{

[Link]("I/O error occurred: "+ioe);


C
}
N
}

}
SY

We will see a proper error message "File Not Found!" on the console because there is no such file in that location.
U
VT

Unchecked Exceptions

The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these
exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn't
handle or declare it, the program would not give a compilation error. Usually, it occurs when the user provides bad
data during the interaction with the program.

Note: The RuntimeException class is able to resolve all the unchecked exceptions because of the child-parent
relationship.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 28


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]

class UncheckedExceptionExample1
{
public static void main(String args[])
{
int a = 35;
int zero = 0;
int result = a/zero;
//Give Unchecked Exception here.
[Link](result);

.IN
}
}
C
In the above program, we have divided 35 by 0. The code would be compiled successfully, but it will throw an
N
ArithmeticException error at runtime. On dividing a number by 0 throws the divide by zero exception that is a
uncheck exception.
SY

Output:
U
VT

[Link]

class UncheckedException1

public static void main(String args[])

{
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 29
Object Oriented Programming with JAVA(BCS306A) Module-4

int num[] ={10,20,30,40,50,60};

[Link](num[7]);

Output:

.IN
C
In the above code, we are trying to get the element located at position 7, but the length of the array is 6. The code
compiles successfully, but throws the ArrayIndexOutOfBoundsException at runtime.
N

User-defined Exception
SY

In Java, we already have some built-in exception classes like

ArrayIndexOutOfBoundsException
U

NullPointerException, and ArithmeticException.


VT

These exceptions are restricted to trigger on some predefined conditions. In Java, 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

Let's write a Java program and create user-defined exception.


[Link]
import [Link].*;
class UserDefinedException
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 30
Object Oriented Programming with JAVA(BCS306A) Module-4

{
public static void main(String args[])
{
try
{
throw new NewException(5);
}
catch(NewException ex)
{
[Link](ex) ;
}

.IN
}
}
C
class NewException extends UserDefinedException
N
{
int x;
SY

NewException(int y)
{
U

x=y;
}
VT

public String toString()


{
return ("Exception value = "+x) ;
}
}
Output:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 31


Object Oriented Programming with JAVA(BCS306A) Module-4

Description:

In the above code, we have created two classes, i.e., UserDefinedException and NewException.
The UserDefinedException has our main method, and the NewException class is our user-defined exception class,
which extends exception. In the NewException class, we create a variable x of type integer and assign a value to it
in the constructor. After assigning a value to that variable, we return the exception message.

.IN
In the UserDefinedException class, we have added a try-catch block. In the try section, we throw the exception,
i.e., NewException and pass an integer to it. The value will be passed to the NewException class and return a
message. We catch that message in the catch block and show it on the screen.
C
Difference Between Checked and Unchecked Exception
N

[Link] Checked Exception Unchecked Exception


SY

1. These exceptions are checked at compile These exceptions are just opposite to the
time. These exceptions are handled at checked exceptions. These exceptions are not
U

compile time too. checked and handled at compile time.


VT

2. These exceptions are direct subclasses of They are the direct subclasses of the
Exception but not extended from RuntimeException class.
RuntimeException class.

3. The code gives a compilation error in the The code compiles without any error because
case when a method throws a checked the exceptions escape the notice of the
exception. The compiler is not able to compiler. These exceptions are the results of
handle the exception on its own. user-created errors in programming logic.

4. These exceptions mostly occur when the These exceptions occur mostly due to
probability of failure is too high. programming mistakes.

5. Common checked exceptions include Common unchecked exceptions include


IOException, DataAccessException, ArithmeticException, InvalidClassException,
InterruptedException, etc. NullPointerException, etc.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 32
Object Oriented Programming with JAVA(BCS306A) Module-4

6. These exceptions are propagated using the These are automatically propagated.
throws keyword.

7. It is required to provide the try-catch and In the case of unchecked exception it is not
try-finally block to handle the checked mandatory.
exception.

Bugs or errors that we don't want and restrict the normal execution of the programs are referred to as exceptions.

ArithmeticException,
ArrayIndexOutOfBoundExceptions,
ClassNotFoundExceptions etc. are come in the category of Built-in Exception. Sometimes, the built-in
exceptions are not sufficient to explain or describe certain situations. For describing these situations, we have to

.IN
create our own exceptions by creating an exception class as a subclass of the Exception class. These types of
exceptions come in the category of User-Defined Exception. C
Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the
N
exception.
SY

[Link]

public class JavaExceptionExample


U

{
public static void main(String args[])
VT

{
try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
//rest code of the program

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 33


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]("rest of the code...");


}
}
Tet Now

Output:

Exception in thread main [Link]:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

Common Scenarios of Java Exceptions

.IN
There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs


C
If we divide any number by zero, there occurs an ArithmeticException.
N
1. int a=50/0;//ArithmeticException
SY

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
U

1. String s=null;
VT

2. [Link]([Link]());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we
have a string variable that has characters; converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=[Link](s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to
occur ArrayIndexOutOfBoundsException. Consider the following statements.

1. int a[]=new int[5];


Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 34
Object Oriented Programming with JAVA(BCS306A) Module-4

2. a[10]=50; //ArrayIndexOutOfBoundsException

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.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try
.IN
C
{
N
//code that may throw an exception
SY

catch(Exception_class_Name ref)
U

}
VT

Syntax of try-finally block

try

//code that may throw an exception

finally

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 35


Object Oriented Programming with JAVA(BCS306A) Module-4

Java catch block

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.

Internal Working of Java try-catch block

.IN
C
N
SY
U

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:
VT

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest
of the code is executed.

Problem without exception handling


Let's try to understand the problem if we don't use a try-catch block.
Example 1
[Link]
public class TryCatchExample1

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 36


Object Oriented Programming with JAVA(BCS306A) Module-4

{
public static void main(String[] args)
{
int data=50/0; //may throw exception
[Link]("rest of the code");
}
}
Test it Now
Output:
Exception in thread "main" [Link]: / by zero

.IN
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).

Solution by exception handling


C
Let's see the solution of the above problem by a java try-catch block.
N
Example 2
SY

[Link]

public class TryCatchExample2


U

{
VT

public static void main(String[] args)

try

int data=50/0; //may throw exception

//handling the exception

catch(ArithmeticException e)
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 37
Object Oriented Programming with JAVA(BCS306A) Module-4

[Link](e);

[Link]("rest of the code");

}
Test it Now

.IN
Output:

[Link]: / by zero
C
rest of the code
N
As displayed in the above example, the rest of the code is executed, i.e., the rest of the code statement is printed.
SY
U
VT

Example 3
Let's see an example to print a custom message on exception.
[Link]
public class TryCatchExample3
{

public static void main(String[] args)


{

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 38


Object Oriented Programming with JAVA(BCS306A) Module-4

try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero");
}
}

}
.IN
C
Test it Now
N
Output:
Can't divided by zero
SY

Java Catch Multiple Exceptions


U

Java Multi-catch block


VT

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.

Flowchart of Multi-catch Block

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 39


Object Oriented Programming with JAVA(BCS306A) Module-4

.IN
Example 1
Let's see a simple example of java multi-catch block.
C
[Link]
public class MultipleCatchBlock1
N
{
SY

public static void main(String[] args)


{
try
U

{
VT

int a[]=new int[5];


a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 40


Object Oriented Programming with JAVA(BCS306A) Module-4

catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}}
Output:
Arithmetic Exception occurs
rest of the code
Java Nested try block

.IN
In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that
we enter a statement in try block, context of that exception is pushed onto the stack.

For example,
C
the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can
N
handle the ArithemeticException (division by zero).
SY

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.
U

Syntax:
VT

....

//main try block

try

statement 1;

statement 2;

//try catch block within another try block

try

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 41


Object Oriented Programming with JAVA(BCS306A) Module-4

statement 3;

statement 4;

//try catch block within nested try block

try

statement 5;

statement 6;

.IN
}

catch(Exception e2)
C
{
N
//exception message
SY

}
U

catch(Exception e1)
VT

//exception message

//catch block of parent (outer) try block

catch(Exception e3)

//exception message

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 42


Object Oriented Programming with JAVA(BCS306A) Module-4

....
Java Nested try Example
Example 1
Let's see an example where we place a try block within another try block for two different exceptions.
[Link]
public class NestedTryBlock
{
public static void main(String args[])
{

.IN
//outer try block
try
C
{
//inner try block 1
N
try
SY

{
[Link]("going to divide by 0");
int b =39/0;
U

}
VT

//catch block of inner try block 1


catch(ArithmeticException e)
{
[Link](e);
}
//inner try block 2
try
{
int a[]=new int[5];

//assigning the value out of array bounds

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 43


Object Oriented Programming with JAVA(BCS306A) Module-4

a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)

.IN
{
[Link]("handled the exception (outer catch)");
C
}
N
[Link]("normal flow..");
SY

}
}
U

Output:
VT

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.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 44


Object Oriented Programming with JAVA(BCS306A) Module-4

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.

The finally block follows the try-catch block.

Flowchart of finally block

.IN
C
N
SY
U
VT

Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).

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.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 45


Object Oriented Programming with JAVA(BCS306A) Module-4

Usage of Java finally

Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur

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.

[Link]
class TestFinallyBlock

public static void main(String args[])

.IN
{

Try
C
{
N
//below code do not throw any exception
SY

int data=25/5;

[Link](data);
U

}
VT

//catch won't be executed

catch(NullPointerException e)

[Link](e);

//executed regardless of exception occurred or not

finally

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 46


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]("finally block is always executed");

[Link]("rest of the code...");

}
Output:

.IN
Case 2: When an exception occurs but not handled by the catch block
Let's see the following example. Here, the code throws an exception however the catch block cannot handle it.
C
Despite this, the finally block is executed after the try block and then the program terminates abnormally.
N
[Link]
public class TestFinallyBlock1
SY

{
public static void main(String args[])
{
U

try
VT

{
[Link]("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
[Link](data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e)
{
[Link](e);

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 47


Object Oriented Programming with JAVA(BCS306A) Module-4

}
//executes regardless of exception occured or not
finally
{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Output:

.IN
C
N
SY
U
VT

Case 3: When an exception occurs and is handled by the catch block

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.

[Link]

public class TestFinallyBlock2


{
public static void main(String args[])
{
try
{

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 48


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]("Inside try block");


//below code throws divide by zero exception
int data=25/0;
[Link](data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e)
{
[Link]("Exception handled");
[Link](e);
}

//executes regardless of exception occured or not


.IN
C
finally
N
{
[Link]("finally block is always executed");
SY

}
[Link]("rest of the code...");
U

}
}
VT

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 [Link]() or by causing a fatal
error that causes the process to abort).

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 49


Object Oriented Programming with JAVA(BCS306A) Module-4

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.

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 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,

.IN
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.

The syntax of the Java throw keyword is given below.


C
throw Instance i.e.,
N
1. throw new exception_class("error message");
SY

Let's see the example of throw IOException.


U

1. throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception is the sub class of
VT

Throwable and the user-defined exceptions usually extend the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
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.
[Link]
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.
public class TestThrow1
{ //function to check if person is eligible to vote or not
public static void validate(int age)
{

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 50


Object Oriented Programming with JAVA(BCS306A) Module-4

if(age<18)
{ //throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else
{
[Link]("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[])

.IN
{
//calling the function
C
validate(13);
N
[Link]("rest of the code...");
}
SY

}
Output:
U
VT

The above code throw an unchecked exception. Similarly, we can also throw unchecked and user defined
exceptions.
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.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked exception in Java. A checked exception is
everything else under the Throwable class.
[Link]

import [Link].*;

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 51


Object Oriented Programming with JAVA(BCS306A) Module-4

public class TestThrow2


{

//function to check if person is eligible to vote or not


public static void method() throws FileNotFoundException
{

FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\[Link]");


BufferedReader fileInput = new BufferedReader(file);

throw new FileNotFoundException();


.IN
C
N
}
//main method
SY

public static void main(String args[])


{
U

try
{
VT

method();
}
catch (FileNotFoundException e)
{
[Link]();
}
[Link]("rest of the code...");
}
}
Output:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 52


Object Oriented Programming with JAVA(BCS306A) Module-4

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.

[Link]

// class represents user-defined exception


class UserDefinedException extends Exception

.IN
{
public UserDefinedException(String str)
{
C
// Calling constructor of parent Exception
N
super(str);
SY

}
}
// Class that uses above MyException
U

public class TestThrow3


VT

{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
[Link]("Caught the exception");
// Print the message from MyException object
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 53
Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]([Link]());
}
}
}

Output:

.IN
C
Java throws keyword
N
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there
SY

may occur an exception. So, it is better for the programmer to provide the exception handling code so that the
normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such
U

as NullPointerException, it is programmers' fault that he is not checking the code before it being used.
VT

Syntax of Java throws

return_type method_name() throws exception_class_name

//method code

Which exception should be declared?

Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 54
Object Oriented Programming with JAVA(BCS306A) Module-4

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws Example

Let's see the example of Java throws clause which describes that checked exceptions can be propagated by throws
keyword.

[Link]

import [Link];

class Testthrows1

.IN
{

void m()throws IOException


C
{
N
throw new IOException("device error");//checked exception
SY

void n()throws IOException

{
U

m();
VT

void p()

try

n();

catch(Exception e)

[Link]("exception handled");
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 55
Object Oriented Programming with JAVA(BCS306A) Module-4

public static void main(String args[])

Testthrows1 obj=new Testthrows1();

obj.p();

[Link]("normal flow...");

.IN
Output:

exception handled
C
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or declare the exception.
N
There are two cases:
SY

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.
U

Case 1: Handle Exception Using try-catch block


VT

In case we handle the exception, the code will be executed fine whether exception occurs during the program or not.

[Link]

import [Link].*;

class M

void method()throws IOException

throw new IOException("device error");

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 56


Object Oriented Programming with JAVA(BCS306A) Module-4

public class Testthrows2

public static void main(String args[])

try

M m=new M();

[Link]();

.IN
}

catch(Exception e)
C
{
N
[Link]("exception handled");

}
SY

[Link]("normal flow...");
U

}
VT

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.

Let's see examples for both the scenario.


A) If exception does not occur
[Link]
import [Link].*;

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 57


Object Oriented Programming with JAVA(BCS306A) Module-4

class M
{
void method()throws IOException
{
[Link]("device operation performed");
}
}
class Testthrows3
{
public static void main(String args[])throws IOException //declare exception
{

.IN
M m=new M();
[Link]();
C
N
[Link]("normal flow...");
} }
SY

Output:
device operation performed
normal flow...
B) If exception occurs
U

[Link]
import [Link].*;
VT

class M
{
void method()throws IOException
{
throw new IOException("device error");
}
}
class Testthrows4
{
public static void main(String args[])throws IOException //declare exception
{
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 58
Object Oriented Programming with JAVA(BCS306A) Module-4

M m=new M();
[Link]();
[Link]("normal flow...");
} }
Output:

Difference between throw and throws

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.

.IN
There are many differences between throw and throws keywords. A list of differences between throw and throws
are given below: C
Sr. Basis of throw throws
no. Differences
N
SY

1. Definition Java throw keyword is used throw Java throws keyword is used in
an exception explicitly in the code, the method signature to declare
inside the function or the block of an exception which might be
code. thrown by the function while
U

the execution of the code.


VT

2. Type of exception Using throw keyword, we can only Using throws keyword, we can
propagate unchecked exception i.e., declare both checked and
the checked exception cannot be unchecked exceptions. However,
propagated using throw only. the throws keyword can be used
to propagate checked exceptions
only.

3. Syntax The throw keyword is followed by The throws keyword is


an instance of Exception to be followed by class names of
thrown. Exceptions to be thrown.

4. Declaration throw is used within the method. throws is used with the method
signature.

5. Internal We are allowed to throw only one We can declare multiple


implementation exception at a time i.e. we cannot exceptions using throws
throw multiple exceptions. keyword that can be thrown by
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 59
Object Oriented Programming with JAVA(BCS306A) Module-4

the method. For example,


main() throws IOException,
SQLException.

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:

Sr.
Key final finally finalize

.IN
no.

1. Definition final is the keyword finally is the block in finalize is the method in
C
and access modifier Java Exception Java which is used to
which is used to apply Handling to execute perform clean up
restrictions on a class, the important code processing just before
N
method or variable. whether the exception object is garbage
occurs or not. collected.
SY

2. Applicable to Final keyword is used Finally block is always finalize() method is used
with the classes, related to the try and with the objects.
U

methods and variables. catch block in


exception handling.
VT

3. Functionality (1) Once declared, (1) finally block runs finalize method performs
final variable becomes the important code the cleaning activities
constant and cannot be even if exception with respect to the object
modified. occurs or not. before its destruction.
(2) final method (2) finally block cleans
cannot be overridden up all the resources
by sub class. used in try block
(3) final class cannot
be inherited.

4. Execution Final method is Finally block is finalize method is


executed only when executed as soon as the executed just before the
we call it. try-catch block is object is destroyed.
executed.
It's execution is not
dependant on the
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 60
Object Oriented Programming with JAVA(BCS306A) Module-4

exception.

Java final Example

Let's consider the following example where we declare final variable age. Once declared it cannot be modified.

[Link]

public class FinalExampleTest

//declaring final variable

final int age = 18;

.IN
void display()

{
C
// reassigning value to age variable
N
// gives compile time error
SY

age = 55;

}
U

public static void main(String[] args)


VT

FinalExampleTest obj = new FinalExampleTest();

// gives compile time error

[Link]();

}
Output:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 61


Object Oriented Programming with JAVA(BCS306A) Module-4

In the above example, we have declared a variable final. Similarly, we can declare the methods and classes final
using the final keyword.

Java finally Example

Let's see the below example where the Java code throws an exception and the catch block handles that exception.
Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.

.IN
[Link]

public class FinallyExample


C
{
N
public static void main(String args[])
SY

try
U

{
VT

[Link]("Inside try block");

// below code throws divide by zero exception

int data=25/0;

[Link](data);

// handles the Arithmetic Exception / Divide by zero exception

catch (ArithmeticException e)

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 62


Object Oriented Programming with JAVA(BCS306A) Module-4

[Link]("Exception handled");

[Link](e);

// executes regardless of exception occurred or not

finally

[Link]("finally block is always executed");

.IN
[Link]("rest of the code...");

}
C
}
N
Output:
SY
U
VT

Java finalize Example

[Link]

public class FinalizeExample

public static void main(String[] args)

{
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 63
Object Oriented Programming with JAVA(BCS306A) Module-4

FinalizeExample obj = new FinalizeExample();

// printing the hashcode

[Link]("Hashcode is: " + [Link]());

obj = null;

// calling the garbage collector using gc()

[Link]();

[Link]("End of the garbage collection");

.IN
// defining the finalize method

protected void finalize()


C
{
N
[Link]("Called the finalize() method");
SY

}
U

Output:
VT

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.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 64


Object Oriented Programming with JAVA(BCS306A) Module-4

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.
Why use custom exceptions?
Java exceptions cover almost all the general type of exceptions that may occur in the programming. However, we
sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

o To catch and provide specific treatment to a subset of existing Java exceptions.


o Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for
the application users or the developers to understand the exact problem.

In order to create custom exception, we need to extend Exception class that belongs to [Link] package.

.IN
Consider the following example, where we create a custom exception named WrongFileNameException:
public class WrongFileNameException extends Exception

{
C
public WrongFileNameException(String errorMessage)
N
{
SY

super(errorMessage);

}
U

}
VT

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.

[Link]
// class representing custom exception
class InvalidAgeException extends Exception
{

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 65


Object Oriented Programming with JAVA(BCS306A) Module-4

public InvalidAgeException (String str)


{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{
// method to check the age

.IN
static void validate (int age) throws InvalidAgeException
{
C
if(age < 18)
N
{
SY

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
U

}
else
VT

{
[Link]("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 66


Object Oriented Programming with JAVA(BCS306A) Module-4

validate(13);
}
catch (InvalidAgeException ex)
{
[Link]("Caught the exception");

// printing the message from InvalidAgeException object


[Link]("Exception occured: " + ex);
}

[Link]("rest of the code...");

.IN
}
}
C
Output:
N
SY
U

Example 2:
VT

[Link]
// class representing custom exception
class MyCustomException extends Exception
{

}
// class that uses custom exception MyCustomException
public class TestCustomException2
{ // main method
public static void main(String args[])
{
try

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 67


Object Oriented Programming with JAVA(BCS306A) Module-4

{
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex)
{
[Link]("Caught the exception");
[Link]([Link]());
}
[Link]("rest of the code...");
}

.IN
}

Output:
C
N
SY
U

Chained Exceptions :

Chained Exceptions in Java


VT

In Java, a chained exception is a technique that enables programmers to associate one Exception with another. By
providing additional information about a specific exception, debugging can be made easier. A chained exception is
created by wrapping an existing exception in a new exception, which becomes the root cause of the new Exception.

The new Exception can provide additional information, while the original Exception contains the actual error
message and stack trace. It makes it easier to determine and fix the problem's source. Chained exceptions are
especially useful when an exception is thrown due to another exception.

In Java, a chained exception is created using one of the constructors of the exception class.

Throwable Class

Constructors and methods for supporting chained exceptions are available in the Throwable class. Let's start by
taking a look at the constructors.

Throwable(Throwable cause): A Java constructor creates a new exception object with a specified cause exception.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 68


Object Oriented Programming with JAVA(BCS306A) Module-4

Throwable(String desc, Throwable cause): A Java constructor creates a new Throwable object with a message
and a cause. It allows for chaining exceptions and providing more detailed information about errors.

In Java, the following Throwable class methods enable chained exceptions:

getCause(): It is a Java method of the Throwable class that returns the cause of the current Exception. It allows for
accessing the Exception or error that triggered the current Exception to be thrown.

initCause() method: determines the reason for the calling Exception.

Example of Chained Exception:

Filename: [Link]

1. public class ChainedExceptionExample {

.IN
2. public static void main(String[] args) {
3. try {
4. String s = null;
C
5. int num = [Link](s); // the line will throw a NumberFormatException
6. } catch (NumberFormatException e) {
N
7. // create a new RuntimeException with the message "Exception."
8. RuntimeException ex = new RuntimeException("Exception");
SY

9.

// set the cause of the new Exception to a new NullPointerException with the message " It is actual ca
U

use of the exception "


VT

10. [Link](new NullPointerException("It is actual cause of the exception"));


11. // throw the new Exception with the chained Exception
12. throw ex;
13. }
14. }
15. }

Output:

Exception in thread "main" [Link]: Exception at


[Link]([Link])
Caused by: [Link]: It is actual cause of the exception at ChainedExceptio

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 69


Object Oriented Programming with JAVA(BCS306A) Module-4

.IN
C
N
SY
U
VT

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 70

You might also like