Module 4
Module 4
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
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
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
[Link] Package
[Link] of package
[Link] package
1. By import packagename.*
2. By import [Link]
4. Subpackage
6. -classpath switch
.IN
7. 4 ways to load the class file or jar file
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
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
.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
[Link]("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
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).
You need to use fully qualified name e.g. [Link] etc to run the class.
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
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
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.
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()
{
[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
It is generally used when two packages have same class name e.g. [Link] and [Link] packages contain Date class.
VT
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
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
There is a scenario, I want to put the class file of [Link] source file in classes folder of c: drive. For example:
VT
{
VT
[Link]("Welcome to package");
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the
class file resides.
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells where to look for class
file. For example:
Output:Welcome to package
o 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.
class A
{
}
class B
{
}
public class C
{
}
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
{
}
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.
.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
Private Y N N N
VT
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
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
[Link]("Hello java");
.IN
public class Simple
{
C
public static void main(String args[])
N
{
A obj=new A();
SY
}
VT
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()
[Link]("Hello java");
.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
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()
[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
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.
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
.IN
[Link]("Hello");
}
C
}
//save by [Link]
N
package mypack;
SY
import pack.*;
U
class B extends A
VT
[Link]();
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
//save by [Link]
package pack;
public class A
[Link]("Hello");
.IN
}
}
C
//save by [Link]
N
package mypack;
SY
import pack.*;
U
class B
VT
[Link]();
}
Output:Hello
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
}
}
VT
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
[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.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at
runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IO Exception, SQL
Exception, RemoteException, etc.
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.
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:
.IN
C
N
SY
U
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)
.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,
2) Unchecked Exception
The classes that inherit the Runtime Exception are known as unchecked exceptions.
For example,
Arithmetic Exception,
NullPointerException,
ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable.
OutOfMemoryError,
VirtualMachineError,
.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.
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.
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.
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
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
.IN
{
[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:
Output:
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
...
...
If we compile and run the code, the errors will disappear, and we will see the data of the file.
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
{
VT
try
catch(FileNotFoundException fnfe)
int m;
try
[Link]((char)m);
file_data.close();
catch(IOException ioe)
.IN
{
}
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.
[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
{
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 29
Object Oriented Programming with JAVA(BCS306A) Module-4
[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
ArrayIndexOutOfBoundsException
U
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
{
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
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
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
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.
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 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
Output:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
.IN
There are given some scenarios where unchecked exceptions may occur. They are as follows:
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
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
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to
occur ArrayIndexOutOfBoundsException. Consider the following statements.
2. a[10]=50; //ArrayIndexOutOfBoundsException
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.
try
.IN
C
{
N
//code that may throw an exception
SY
catch(Exception_class_Name ref)
U
}
VT
try
finally
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.
.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
But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest
of the code is executed.
{
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).
[Link]
{
VT
try
catch(ArithmeticException e)
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 37
Object Oriented Programming with JAVA(BCS306A) Module-4
[Link](e);
}
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
{
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
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.
.IN
Example 1
Let's see a simple example of java multi-catch block.
C
[Link]
public class MultipleCatchBlock1
N
{
SY
{
VT
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
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
....
try
statement 1;
statement 2;
try
statement 3;
statement 4;
try
statement 5;
statement 6;
.IN
}
catch(Exception e2)
C
{
N
//exception message
SY
}
U
catch(Exception e1)
VT
//exception message
catch(Exception e3)
//exception message
....
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
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.
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.
.IN
C
N
SY
U
VT
Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
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.
Let's see the different cases where Java finally block can be used.
Let's see the below example where the Java program does not throw any exception, and the finally block is executed
after the try block.
[Link]
class TestFinallyBlock
.IN
{
Try
C
{
N
//below code do not throw any exception
SY
int data=25/5;
[Link](data);
U
}
VT
catch(NullPointerException e)
[Link](e);
finally
}
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);
}
//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
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]
}
[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).
In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead of
runtime and we can create custom exceptions making the code recovery and debugging easier.
We specify the exception object which is to be thrown. The Exception has some message with it that provides the
error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a
custom exception. We will discuss custom exceptions later in this section.
We can also define our own set of conditions and throw an exception explicitly using throw keyword. For example,
.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.
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.
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.
import [Link].*;
try
{
VT
method();
}
catch (FileNotFoundException e)
{
[Link]();
}
[Link]("rest of the code...");
}
}
Output:
[Link]
.IN
{
public UserDefinedException(String str)
{
C
// Calling constructor of parent Exception
N
super(str);
SY
}
}
// Class that uses above MyException
U
{
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
//method code
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
{
{
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
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
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
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...
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:
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
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.
4. Declaration throw is used within the method. throws is used with the method
signature.
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
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.
exception.
Let's consider the following example where we declare final variable age. Once declared it cannot be modified.
[Link]
.IN
void display()
{
C
// reassigning value to age variable
N
// gives compile time error
SY
age = 55;
}
U
[Link]();
}
Output:
In the above example, we have declared a variable final. Similarly, we can declare the methods and classes final
using the final keyword.
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]
try
U
{
VT
int data=25/0;
[Link](data);
catch (ArithmeticException e)
[Link]("Exception handled");
[Link](e);
finally
.IN
[Link]("rest of the code...");
}
C
}
N
Output:
SY
U
VT
[Link]
{
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 63
Object Oriented Programming with JAVA(BCS306A) Module-4
obj = null;
[Link]();
.IN
// defining the finalize method
}
U
Output:
VT
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.
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
{
.IN
static void validate (int age) throws InvalidAgeException
{
C
if(age < 18)
N
{
SY
}
else
VT
{
[Link]("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
[Link]("Caught the exception");
.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
{
// 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 :
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.
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.
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.
Filename: [Link]
.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
Output:
.IN
C
N
SY
U
VT