0% found this document useful (0 votes)
428 views

OOPS With Java BCS306A Mod 4 Notes For Exam @vtunetwork

Uploaded by

akashdinesh206
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)
428 views

OOPS With Java BCS306A Mod 4 Notes For Exam @vtunetwork

Uploaded by

akashdinesh206
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
You are on page 1/ 33

1

REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Object Oriented Programming with JAVA


BCS306A
Academic Year 2023 – 24
Lecture Notes

Name Of the Programme B.E - CSE

Scheme 2022

Year and Semester II Year III Semester

S Subject Code BCS306A

Name of the Faculty K RADHIKA

Prof K RADHIKA, Dept of CSE SSCE, Anekal


2
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
MODULE 4

Syllabus:
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.

Packages
When we have more than one class in our program, usually we give unique names to classes. In a real-
time development, as the number of classes increases, giving unique meaningful name for each class will
be a problem. To avoid name-collision in such situations, Java provides a concept of packages.
A package is a collection of classes. The package is both a naming and a visibility control mechanism.
You can define classes inside a package that are not accessible by code outside that package. You can also
define class members that are only exposed to other members of the same package. This allows your
classes to have intimate knowledge of each other, but not expose that knowledge to the rest of the world.

J ava packages are classified into 2 types


1. Java API(Application Program Interface) packages (or) Predefined packages
(or) Built in packages. These packages are defined by the system. Some of the
example for system defined packages are java.lang, java.util, java.io etc.,
2. User defined packages: These packages are defined by the users.
Advantage of Java Package
1. J ava 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.
Example J ava Package:

Prof K RADHIKA, Dept of CSE SSCE, Anekal


3
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Defining a Package
To create a package, include a package command as the first statement in a Java source file. Any class
declared within that file will belong to the specified package. If you omit the package statement, the class
names are put into the default package, which has no name.

General form of the package statement:


package pkg;
Example – package MyPackage;
Java uses file system directories to store packages. We save the program with number.java and compile
the package as javac number.java. Due to this compilation mypack directory is automatically created and
.class file is stored in that directory.
The package statement simply specifies to which package the classes defined in a file belong.

One can create a hierarchy of packages. To do so, simply separate each package name from the one above
it by use of a period. The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system. For example, a
package declared as package java.awt.image; needs to be stored in java\awt\image in a Windows
environment. You cannot rename a package without renaming the directory in which the classes are
stored.
Finding Packages and CLASSPATH
As we have seen, packages are reflected with directories. This will raise the question that - how does Java
run-time know where to look for the packages that we create?
• By default, Java run-time uses current working directory as a starting point. So, if our package is in
a sub-directory of current working directory, then it will be found.
• We can set directory path using CLASSPATH environment variable.
We can use –classpath option with javac and java to specify path of our classes

Assume that we have created a package MyPackage. When the second two options are used, the class path
must not include MyPackage. It must simply specify the path to MyPackage. For example, in a
Windows environment, if the path to MyPackage is
C:\MyPrograms\Java\MyPackage

Then the class path to MyPackage is


C:\MyPrograms\Java

Prof K RADHIKA, Dept of CSE SSCE, Anekal


4
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Consider the program given below –


package MyPackage;
class Test
{
int a, b;
Test(int x, int y)
{
a=x; b=y;
}
void disp()
{
System.out.println("a= "+a+" b= "+b);
}
}
class PackDemo
{
public static void main(String args[])
{
Test t=new Test(2,3);
t.disp();
}
}

Importing Packages
Java includes the import statement to bring certain classes, or entire packages, into visibility. Once
imported, a class can be referred to directly, using only its name.

In a Java source file, import statements occur immediately following the package statement (if it exists)
and before any class definitions. The general form of the import statement is:
import pkg1[.pkg2].(classname|*);

For example,
import java.util.Date;
import java.io.*;

Prof K RADHIKA, Dept of CSE SSCE, Anekal


5
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

The star form may increase compilation time—especially if you import several large packages. For this
reason it is a good idea to explicitly name the classes that you want to use rather than importing whole
packages. However, the star form has absolutely no effect on the run-time performance or size of your
classes.

All the standard Java classes included with Java are stored in a package called java. The basic language
functions are stored in a package inside of the java package called java.lang. Normally, you must import
every package or class that you want to use, but since Java is useless without much of the functionality in
java.lang, it is implicitly imported by the compiler for all programs. This is equivalent to the following
line being at the top of all your programs:

import java.lang.*;

If a class with the same name exists in two different packages that you import using the star form, the
compiler will remain silent, unless you try to use one of the classes. In that case, you will get a compile-
time error and must explicitly name the class specifying its package.

The import statement is optional. Any place you use a class name, you can use its fully qualified name,
which includes its full package hierarchy. For example,
import java.util.*;
class MyDate extends Date
{ ……………}

Can be written as –
class MyDate extends java.util.Date
{ …}

Develop a JAVA program to create a package named mypack and import & implement it in a suitable
class.
To create a Java package named mypack and import it in a suitable class, you can follow these steps in
Eclipse:
1. Open Eclipse and create a new Java project:
o Go to File > New > Java Project.
o Enter the project name, e.g., "MyPackageDemo," and click Finish.
2. Create a package named mypack:
o Right-click on the "src" folder within your project.
o Choose New > Package.
o Enter "mypack" as the package name and click Finish.
3. Create a class within the mypack package:

Prof K RADHIKA, Dept of CSE SSCE, Anekal


6
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
oRight-click on the mypack package.
o Choose New > Class.
o Enter a class name, e.g., "Circle" and select the option to include the public static void
main(String[] args) method.
o Click Finish.
4. Now, you can implement the code to calculate the area of a circle in the Circle class:

mypack/Circle.java
package mypack; // Import the mypack package
import java.util.Scanner;
public class Circle
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
double area = calculateCircleArea(radius);
System.out.println("The area of the circle is: " + area);
scanner.close();
}
public static double calculateCircleArea(double radius)
{
return Math.PI * radius * radius;
}
}

To use the mypack package in another class and calculate the area of a circle using the import statement,
you can follow these steps:

1. Create a new Java class in your project. Let's call it MainClass in a different package (e.g., myapp).
2. Import the mypack package in your MainClass and use it to calculate the area of a circle.
3. To run the program, right-click on the MainClass and select "Run As" > "Java Application."
myapp/MainClass.java
package myapp; // This is the package for MainClass
import mypack.Circle; // Import the Circle class from mypack
public class MainClass
{
public static void main(String[] args)
{
Circle circle = new Circle(); // Create an instance of the Circle class

Prof K RADHIKA, Dept of CSE SSCE, Anekal


7
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
double radius = 5.0; // You can set your own radius here
double area = circle.calculateCircleArea(radius); // Use the method from the Circle class
System.out.println("The area of the circle is: " + area);
}
}
Output:
The area of the circle is: 78.53981633974483

Sub packages: It is also possible to create sub packages for the main package like creating subfolders .
Syntax: package pack1.pack2;
Where pack1 is the main package and pack2 is the sub package.
Example:
package pack1;
public class X
{
public void show()
{
System.out.println(“Super”);
}
}
package pack1.pack2; // creating pack2 under the package pack1
public class Y
{
public void display()
{
System.out.println(“sub”);
}
}
import pack1.X ;
import pack1.pack2.Y;
class check
{
public static void main(String args[])
{
Prof K RADHIKA, Dept of CSE SSCE, Anekal
8
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
X obj=new X ();
obj.show();
Y obj1=new Y();
obj1.display();
}
}
Access Protection
Java provides many levels of protection to allow fine-grained control over the visibility of variables and
methods within classes, subclasses, and packages. Classes and packages are both means of encapsulating
and containing the name space and scope of variables and methods. Packages act as containers for classes
and other subordinate packages. Classes act as containers for data and code. The class is Java’s smallest
unit of abstraction.

Java addresses four categories of visibility for class members:


• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses

Even a class has accessibility feature. A class can be kept as default or can be declared as public. When a
class is declared as public, it is accessible by any other code. If a class has default access, then it can only
be accessed by other code within its same package. When a class is public, it must be the only public
class declared in the file, and the file must have the same name as the class. Accessibility of members of the
class can be better understood using the following table.

Private No Modifier Protected Public


Same class Yes Yes Yes Yes
Same package No Yes Yes Yes
subclass
Same package No Yes Yes Yes
non-subclass
Different package No No Yes Yes
Subclass
Different package No No No Yes
non-subclass

Prof K RADHIKA, Dept of CSE SSCE, Anekal


9
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Exception Handling
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a run-time error. In computer languages that do not support exception handling, errors must
be checked and handled manually—typically using error codes. This approach is as cumbersome as it is
troublesome. Java’s exception handling avoids these problems and, in the process, brings run-time error
management into the object-oriented world.

Exception Handling Fundamentals


An exception is an unexpected event that occurs during program execution. It affects the flow of the
program instructions which can cause the program to terminate abnormally.

An exception can occur for many reasons. Some of them are:

• Invalid user input


• Device failure
• Loss of network connection
• Physical limitations (out of disk memory)
• Code errors
• Opening an unavailable file

A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a
piece of code. When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error. That method may choose to handle the exception itself, or pass
it on. Either way, at some point, the exception is caught and processed.

Exceptions can be generated by the Java run-time system, or they can be manually generated by your
code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or
the constraints of the Java execution environment. Manually generated exceptions are typically used to
report some error condition to the caller of a method.

Java exception handling is managed using five keywords:


• try: A suspected code segment is kept inside try block.
• catch: The remedy is written within catch block.
• throw: Whenever run-time error occurs, the code must throw an exception.
• throws: If a method cannot handle any exception by its own and some subsequent methodsneeds
to handle them, then a method can be specified with throws keyword with its declaration.
• finally: block should contain the code to be executed after finishing try-block.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


10
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

The general form of exception handling is –


try
{
// block of code to monitor errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
...
….
finally
{
// block of code to be executed after try block ends
}

Exception Types
All the exceptions are the derived classes of built-in class Throwable. It has two subclasses
Exception and Error.

Throwable

Exception Error

Customized Exception
(User defined class to
Runtime Exception I/O Exception
handle own)

Exceptions can be caught and handled by the program. When an exception occurs within a method, it
creates an object. This object is called the exception object. It contains information about the exception
such as the name and description of the exception and state of the program when the exception occurred.
Runtime Exception. A runtime exception happens due to a programming error. They are also known as

Prof K RADHIKA, Dept of CSE SSCE, Anekal


11
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
unchecked exceptions.

These exceptions are not checked at compile-time but run-time. Some of the common runtime exceptions
are:

Improper use of an API - IllegalArgumentException


Null pointer access (missing the initialization of a variable) - NullPointerException
Out-of-bounds array access - ArrayIndexOutOfBoundsException
Dividing a number by 0 - ArithmeticExceptionExceptions

IOException An IOException is also known as a checked exception. They are checked by the compiler at
the compile-time and the programmer is prompted to handle these exceptions.

Some of the examples of checked exceptions are:

Trying to open a file that doesn’t exist results in FileNotFoundException


Trying to read past the end of a file

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory,
memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle errors.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


12
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Uncaught Exceptions
Let us see, what happens if we do not handle exceptions.
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object
and then throws this exception. This causes the execution of Exc to stop, because once an exception has
been thrown, it must be caught by an exception handler and dealt with immediately. Since, in the above
program, we have not supplied any exception handlers of our own, so the exception is caught by the
default handler provided by the Java run-time system.

Any un-caught exception is handled by default handler. The default handler displays a string describing
the exception, prints a stack trace from the point at which the exception occurred, and terminates the
program. Here is the exception generated when above example is executed:

java.lang.ArithmeticException: / by zeroat Exc0.main(Exc0.java:6)

The stack trace displays class name, method name, file name and line number causing the exception. Also,
the type of exception thrown viz. ArithmeticException which is the subclass of Exception is displayed.
The type of exception gives more information about what type of error has occurred. The stack trace will
always show the sequence of method invocations that led up to the error.

class Exc1
{
static void subroutine()
{
int d = 0;
int a = 10 / d;
}
public static void main(String args[])
{
Exc1.subroutine();
}
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


13
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
The resulting stack trace from the default exception handler shows how the entire call stack is displayed:
java.lang.ArithmeticException: / by zeroat Exc1.subroutine(Exc1.java:6)
at Exc1.main(Exc1.java:10)

Using try and catch


Handling the exception by our own is very much essential as
• We can display appropriate error message instead of allowing Java run-time to display stack-
trace.
• It prevents the program from automatic (or abnormal) termination.

To handle run-time error, we need to enclose the suspected code within try block.

class Exc2
{
public static void main(String args[])
{
int d, a;

try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

Output:
Division by zero.
After catch statement.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


15
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Multiple Catch Claues


In some cases, more than one exception could be raised by a single piece of code. To handle this type of
situation, you can specify two or more catch clauses, each catching a different type of exception. When
an exception is thrown, each catch statement is inspected in order, and the first one whose type matches
that of the exception is executed. After one catch statement executes, the others are bypassed, and
execution continues after the try/catch block.

class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index : " + e);
}
System.out.println("After try/catch blocks.");
}
}

Here is the output generated by running it both ways:


C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index : java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
Prof K RADHIKA, Dept of CSE SSCE, Anekal
16
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

While using multiple catch blocks, we should give the exception types in a hierarchy of subclass to
superclass. Because, catch statement that uses a superclass will catch all exceptions of its own type plus all
that of its subclasses. Hence, the subclass exception given after superclass exception is never caught and is
a unreachable code, that is an error in Java.

class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
catch(ArithmeticException e) // ERROR - unreachable
{
System.out.println("This is never reached.");
}
}
}

The above program generates error “Unreachable Code”, because ArithmeticException is a subclass of
Exception.

Nested try Statements


The try statement can be nested. That is, a try statement can be inside the block of another try. Each
time a try statement is entered, the context of that exception is pushed on the stack. If an inner try
statement does not have a catch handler for a particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match. This continues until one of the catch statements
succeeds, or until all the nested try statements are exhausted. If no catch statement matches, then the Java
run-time system will handle the exception.
try
{
// parent try block
try
{

Prof K RADHIKA, Dept of CSE SSCE, Anekal


17
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
// child try block

}
catch(ExceptionType1 e1)
{
// child catch block
}
}
catch (ExceptionType2 e1)
{
// parent catch block
}

Points To Remember While Using Nested Try Block


• Child catch block should have specific exception for better code clarity. Parent catch block can have
more generic exception handled so that if child catch block is not able to handle the exception then
parent catch block can handle it.
• There in no restriction on exception hiearchy to be used in child vs parent catch block.
• If a exception is handled correctly in child catch block, then in parent, another exception can be
raised and handled.

public class ExcepTest


{
public static void main(String args[])
{
try
{
int a[] = new int[2];
try
{
int b = 0;
int c = 1/b;
}
catch(Exception e)
{
System.out.println("Exception thrown: " + e);
}
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e)
{

Prof K RADHIKA, Dept of CSE SSCE, Anekal


18
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
System.out.println("Exception thrown: " + e);
}
System.out.println("Out of the block");
}
}

Output:

Exception thrown: java.lang.ArithmeticException: / by zero


Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

In the following example, we're creating an error by dividing a value by 0 in nested try block but we're not
handling in corresponding catch block. As parent try block is handling the exception raised as generic
exception, it captures the exception raised by child catch block and prints the same.

public class ExcepTest


{
public static void main(String args[])
{
try
{
int a[] = new int[2];
try
{
int b = 0;
int c = 1/b;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown: " + e);
}
System.out.println("Access element three :" + a[3]);
}
catch (Exception e)
{
System.out.println("Exception thrown: " + e);
}
System.out.println("Out of the block");
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


19
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
}

Output:

Exception thrown: java.lang.ArithmeticException: / by zero


Out of the block

In the following example, we're creating an error by dividing a value by 0 in nested try block but we're not
handling this kind of exception in any catch block. Now JVM will capture the exception and terminate the
program without printing the last statement.

package com.tutorialspoint;
public class ExcepTest
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
try
{
int b = 0;
int c = 1/b;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown: " + e);
}
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown: " + e);
}
System.out.println("Out of the block");
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.tutorialspoint.ExcepTest.main(ExcepTest.java:10)

Prof K RADHIKA, Dept of CSE SSCE, Anekal


20
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

throw
Till now, we have seen catching the exceptions that are thrown by the Java run-time system. It is possible
for your program to throw an exception explicitly, using the throw statement. The general form of throw
is shown here:
throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive


types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be
used as exceptions.

There are two ways you can obtain a Throwable object:


– using a parameter in a catch clause, or
– creating one with the new operator.

public class TestThrow


{
//defining a method
public static void checkNum(int num)
{
if (num < 1)
{
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else
{
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args)
{
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException:
Number is negative, cannot calculate square
at TestThrow.checkNum(TestThrow.java: 6)
at TestThrow.main (TestThrow.java:16)
Prof K RADHIKA, Dept of CSE SSCE, Anekal
21
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Here, new is used to construct an instance of ArithmeticException. Many of Java’s built-in run-time
exceptions have at least two constructors:
– one with no parameter and
– one that takes a string parameter

When the second form is used, the argument specifies a string that describes the exception.

throws
If a method can cause an exception that it does not handle, it must specify this behavior so that callers of
the method can guard themselves against that exception. You do this by including a throws clause in the
method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.
All other exceptions that a method can throw must be declared in the throws clause. If they are not, a
compile-time error will result.

The general form of a method declaration that includes a throws clause:


type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.

public class TestThrows


{
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
public static void main(String[] args)
{
TestThrows obj = new TestThrows();
try
{
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e)
{
System.out.println("\nNumber cannot be divided by 0");
}
Prof K RADHIKA, Dept of CSE SSCE, Anekal
22
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

System.out.println("Rest of the code..");


}
}

Output:
Number cannot be divided by e
Rest of the code..

Java throw and throws Example


public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
Output:
Inside the method()
caught in main () method

Prof K RADHIKA, Dept of CSE SSCE, Anekal


23
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the
normal flow through the method. Sometimes it is even possible for an exception to cause the method to
return prematurely. This could be a problem in some methods. For example, if a method opens a file upon
entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the
exception-handling mechanism. The finally keyword is designed to address such situations.

The finally clause creates a block of code that will be executed after a try/catch block has completed and
before the next code of try/catch block. The finally block will execute whether or not an exception is
thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the
exception. Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just before the
method returns. The finally clause is optional. However, each try statement requires at least one catch or
a finally clause.

Case 1: When an exception does not occur

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


24
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
//catch won't be executed
catch(NullPointerException e)
{
System.out.println(e);
}
//executed regardless of exception occurred or not
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Output:
5
Finally block is always executed
rest of the code...

Case 2: When an exception occur but not handled by the catch block

public class TestFinallyBlock1


{
public static void main(String args[])
{
try
{
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e)
{
System.out.println(e);
}
//executes regardless of exception occured or not
finally
{
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


25
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Output:
Inside the try block
finally block is always executed Exception in thread "main" java.lang-ArithmeticException: / by zero
at TestFinallyBlock1.main(TestFinallyBlock1.java:9)

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

public class TestFinallyBlock2


{
public static void main(String args[])
{
try
{
System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e)
{
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occured or not


finally
{
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}
Output:
Inside try block
Exception handled
java.lang.ArithmeticException: / by zero finally block is always executed
rest of the code...

Prof K RADHIKA, Dept of CSE SSCE, Anekal


26
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Java’s Built-in Exceptions


Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable
to explain certain error situations. Inside the standard package java.lang, Java defines several exception
classes.

Table: Java’s Unchecked Exceptions


Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined enumerationvalue.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateException Environment or application is in incorrect state.

IllegalThreadStateException Requested operation not compatible with current thread


state.
IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.


NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


27
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Table: Java’s Checked Exceptions


Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.

InterruptedException One thread has been interrupted by another thread.


NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

Creating your own Exception Subclasses


Java provides rich set of built-in exception classes like: ArithmeticException, IOException,
NullPointerException etc. all are available in the java.lang package and used in exception handling. These
exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it
triggers ArithmeticException.
Apart from these classes, Java allows us to create our own exception class to provide own exception
implementation. These type of exceptions are called user-defined exceptions or custom exceptions.
You can create your own exception simply by extending java Exception class. You can define a constructor
for your Exception (not compulsory) and you can override the toString() function to display your
customized message on catch. Lets see an example.
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex = a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Demo
{
static void sum(int a,int b) throws MyException
Prof K RADHIKA, Dept of CSE SSCE, Anekal
28
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)


{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined Exception
}
}
}
Output:
MyException[-10] is less than zero

Although Java’s built-in exceptions handle most common errors, sometimes we may want to create our
own exception types to handle situations specific to our applications. This is achieved by defining a
subclass of Exception class. Your subclasses don’t need to actually implement anything—it is their
existence in the type system that allows you to use them as exceptions. The Exception class does not
define any methods of its own. It inherits those methods provided by Throwable. Thus, all exceptions,
including those that you create, have the methods defined by Throwable available to them.

Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a completedstack
trace. This object can be re-thrown.
Throwable getCause( ) Returns the exception that underlies the current exception.If
there is no underlying exception, null is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


29
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

String getMessage() Returns a description of the exception.


StackTraceElement[] Returns an array that contains the stack trace, one element
getStackTrace() at a time, as an array of StackTraceElement. The method at
the top of the stack is the last method called before the
exception was thrown. This method is found in the first
element of the array. The StackTraceElement class gives
your program access to information about each element in
the trace, such as its method name.
Throwable initCause(Throwable Associates causeExc with the invoking exception as a
causeExc) cause of the invoking exception. Returns a reference to the
exception.
void printStackTrace( ) Displays the stack trace.
void printStackTrace( PrintStream Sends the stack trace to the specified stream.
stream)
void Sends the stack trace to the specified stream.
printStackTrace(PrintWriter
stream)
void setStackTrace( Sets the stack trace to the elements passed in elements.
StackTraceElement This method is for specialized applications, not normal
elements[ ]) use.

String toString( ) Returns a String object containing a description of the


exception. This method is called by println( ) when
outputting a Throwable object.

We may wish to override one or more of these methods in exception classes that we create. Two of the
constructors of Exception are:
Exception( )
Exception(String msg)

Though specifying a description when an exception is created is often useful, sometimes it is better to
override toString( ). The version of toString( ) defined by Throwable (and inherited by Exception) first
displays the name of the exception followed by a colon, which is then followed by your description. By
overriding toString( ), you can prevent the exception name and colon from being displayed. This makes
for a cleaner output, which is desirable in some cases.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


30
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
class MyException extends Exception
{
int marks;

MyException (int m)
{
marks=m;
}

public String toString()


{
return "MyException: Marks cannot be Negative";
}
}
class CustExceptionDemo
{
static void test(int m) throws MyException
{
System.out.println("Called test(): "+m);
if(m<0)
throw new MyException(m);

System.out.println("Normal exit");
}

public static void main(String args[])


{
try{
test(45);
test(-2);
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


31
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Chained Exceptions
Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause
of another exception. For example, consider a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the
divisor to be zero. The method will throw only ArithmeticException to the caller. So the caller would not
come to know about the actual cause of exception. Chained Exception is used in such type of situations.
Constructors Of Throwable class which support chained exceptions in java :
1. Throwable(Throwable cause) :- Where cause is the exception that causes the current exception.
2. Throwable(String msg, Throwable cause) :- Where msg is the exception message and cause is the
exception that causes the current exception.
Methods Of Throwable class which support chained exceptions in java :
1. getCause() method :- This method returns actual cause of an exception.
2. initCause(Throwable cause) method :- This method sets the cause for the calling exception.

Example: ArithmeticException was thrown by the following program but the real cause of exception was
IOException.

import java.io.IOException;
public class ChainedException
{
public static void divide(int a, int b)
{
if(b == 0)
{
ArithmeticException ae = new ArithmeticException("top layer");
ae.initCause(new IOException("cause"));
throw ae;
}
else
{
System.out.println(a/b);
}
}

public static void main(String[] args)


{
try
{
divide(5, 0);
}
Prof K RADHIKA, Dept of CSE SSCE, Anekal
32
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
catch(ArithmeticException ae) {
System.out.println( "caught : " +ae);
System.out.println("actual cause: "+ae.getCause());
}
}
}
Output:
caught:java.lang.ArithmeticException: top layer
actual cause: java.io.IOException: cause

Chained exceptions can be carried on to whatever depth is necessary. Thus, the cause exception can, itself,
have a cause. Be aware that overly long chains of exceptions may indicate poor design. Chained
exceptions are not something that every program will need. However, in cases in which knowledge of an
underlying cause is useful, they offer an elegant solution.

Using Exceptions
Exception handling provides a powerful mechanism for controlling complex programs that have many
dynamic run-time characteristics. It is important to think of try, throw, and catch as clean ways to handle
errors and unusual boundary conditions in your program’s logic. Unlike some other languages in which
error return codes are used to indicate failure, Java uses exceptions. Thus, when a method can fail, have
it throw an exception. This is a cleaner way to handle failure modes.

Note that Java’s exception-handling statements should not be considered a general mechanism for
nonlocal branching. If you do so, it will only confuse your code and make it hard to maintain.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


33
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Develop a JAVA program to raise a custom exception (user defined
exception) for DivisionByZero using try, catch, throw and finally.

import java.util.Scanner;

class DivisionByZeroException extends Exception


{
public DivisionByZeroException(String message)
{
super(message);
}
}

public class CustomExceptionWithUserInput


{
public static void main(String[] args)
{
try
{
int numerator, denominator;

Scanner scanner = new Scanner(System.in);

// Input from the user


System.out.print("Enter the numerator: ");
numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
denominator = scanner.nextInt();

scanner.close();

if (denominator == 0)
{
throw new DivisionByZeroException("Division by zero is
not allowed.");
}

int result = numerator / denominator;


System.out.println("Result of division: " + result);
}
catch (DivisionByZeroException e)
{
System.err.println("Custom Exception Caught: " +
e.getMessage());
} catch (ArithmeticException e)
{
Prof K RADHIKA, Dept of CSE SSCE, Anekal
34
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
System.err.println("Arithmetic Exception Caught: " +
e.getMessage());
}
finally
{
System.out.println("Finally block executed.");
}
}
}

Output:

Enter the numerator: 10


Enter the denominator: 2
Result of division: 5
Finally block executed.

Enter the numerator: 20


Enter the denominator: 0
Finally block executed.
Custom Exception Caught: Division by zero is not allowed.

Prof K RADHIKA, Dept of CSE SSCE, Anekal

You might also like