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

module4_java4

Uploaded by

Shyam Kaushik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

module4_java4

Uploaded by

Shyam Kaushik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Rashtreeya Sikshana Samithi Trust

RV Institute of Technology and


Management®
(Affiliated to VTU, Belagavi)

JP Nagar, Bengaluru – 560076

Department of Computer Science and Engineering

Course Name: Object Oriented Programming with Java


Course Code:
BCS306A
III Semester
2022 Scheme
Prepared By:

Prof Nandita and Prof Syeda Ayesha


Assistant Professor
Department of Computer Science and Engineering,RVITM,
Bengaluru – 560076

Email: [email protected]
[email protected]
RV Institute of Technology and Management®

MODULE 4 PACKAGES AND EXCEPTIONS


Packages:

Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub


packages.To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored. If you omit
the package statement, the class names are put into the default package, which has no name.

This is the general form of the package statement:

package pkg;

Java uses file system directories to store packages. For example, the .class files for any classes
you declare to be part of MyPackage must be stored in a directory called MyPackage.

You can create a hierarchy of packages.

Package pkg1[.pkg2[.pkg3]];

Ex: package java.awt.image;

Advantages of using a package

• Reusability: Reusability of code is one of the most important requirements in the


software industry. Reusability saves time, effort and also ensures consistency. A class
once developed can be reused by any number of programs wishing to incorporate the
class in that particular program.

III- Semester Object Oriented Programming with JAVA(BCS306A) 1


RV Institute of Technology and Management®

• Easy to locate the files.

• In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to ―name-space collisions‖. Packages are a way of avoiding
space collisions.

4.1.2 Package are categorized into two forms

• Built-in Package:-Existing Java package for example java.lang, java.util etc.

• User-defined-package:- Java package created by user to categorized classes as shown in


Fig. 4.1 and interface

Fig. 4.1: Java packages

4.1.3 How to compile & Run java package?


If you are not using any IDE, you need to follow this:

Compile :- javac -d . Simple.java

Run :- java mypack.Simple

III- Semester Object Oriented Programming with JAVA(BCS306A) 2


RV Institute of Technology and Management®

How to access package from another package?


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

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible
but not sub packages. The import keyword is used to make the classes and interface of
another package accessible to the current package.

//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B
{ public static void main(String args[])

{A obj = new A();


obj.msg();

}
}

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;

III- Semester Object Oriented Programming with JAVA(BCS306A) 3


RV Institute of Technology and Management®

public class A{
public void msg(){System.out.println("Hello");}

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

}
}

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible.
Nowthere is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully
qualified nameobj.msg();}}

III- Semester Object Oriented Programming with JAVA(BCS306A) 4


RV Institute of Technology and Management®

Access Specifiers
• private: accessible only in the class
• default : so-called ―package‖ access — accessible only in the same package
• protected: accessible (inherited) by subclasses, and accessible by code in same
package
• public: accessible anywhere the class is accessible, and inherited by subclasses
Notice that private protected is not syntactically legal. Comparison of access specifier is as
shown in Table 4.1

Table 4.1: Comparison of access specifier

III- Semester Object Oriented Programming with JAVA(BCS306A) 5


RV Institute of Technology and Management®

ExceptionHandlinginJava
An exception(or exceptional event )is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is
not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources
that have failed in some manner.

Difference between error and exception

Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example, memory error, hardware error, JVM error etc.

Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions.

Fewexamples–
• Divide By Zero exception
• Null Pointer Exception
• Arithmetic Exception
• Array Index Ou tOf Bounds Exception

Advantages of Exception Handling


• Exceptionhandlingallowsustocontrolthenormalflowoftheprogrambyusing
exception handling in program.
• It hrows an exception whenever a calling method encounters an error providing
that the calling method takes care of that error.
• It also gives us the scope of organizing and differentiating between different error
types using a separate block of codes. This is done with the help of try-catch
blocks.

III- Semester Object Oriented Programming with JAVA(BCS306A) 6


RV Institute of Technology and Management®

Exception hierarchy

Figure3.7:Exception Hierarchy

Java Exception Handling Keywords

Java provides specific keywords for exception handling purposes,


1. try
2. catch
3. finally
4. throw
5. throws

a) try-catch–
try is the start of the block and catch is at the end of try block to handle the
exceptions. We can have multiple catch blocks with a try an try-catch block can be nested
also catch block requires a parameter that should be of type Exception.
A catch block must be associated with a try block. The corresponding catch block
executes if an exception of a particular type occurs within the try block.

III- Semester Object Oriented Programming with JAVA(BCS306A) 7


RV Institute of Technology and Management®

import java.io.*;

public class ExcepTest


{
publicstatic void main(String args[])
{
try{
inta[]=new int[2];
System.out.println("Accesselementthree:"+a[3]);
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("Exceptionthrown:"+e);
}
System.out.println("Outoftheblock");
}
}

For example, if an arithmetic exception occurs in try block then the statements enclosed in
catch block for arithmetic exception executes.

Syntax of try catch in java


try
{
//statementsthatmaycauseanexception
}
catch(exception(type)e(object))
{
//errorhandling code
}

b) Multiple Catch Blocks


A try block can be followed by multiple catch blocks.
If the try block throws an exception, the appropriate catch block (if one exists) will catch it –
catch(Arithmetic Exception e) is a catch block that can catch Arithmetic Exception – catch(Null Pointer
Exception e) is a catch block that can catch Null Pointer Exception

All the statements in the catch block will be executed and then the program continues.
If the exception type of exception, matches with the first catch block it gets caught, if not the
exception is passed down to the next catch block.

classExample2{
public static void main(String args[]){
try{
int a[]=newi nt[7];

III- Semester Object Oriented Programming with JAVA(BCS306A) 8


RV Institute of Technology and Management®

a[4]=30/0;
System.out.println("Firstprintstatementintryblock");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsExceptione){
System.out.println("Warning:
ArrayIndexOutOfBoundsException");
}
catch(Exceptione){
System.out.println("Warning:SomeOtherexception");
}
System.out.println("Outoftry-catchblock...");
}
}

Warning:ArithmeticException
Out of try-catch block...

c) Javafinally block
Java finally block is a block that is used to execute important code such as closing connection,stream etc.Java
finally block is always executed whether exception is handled or not.
Finallyblockisoptionalandcanbeusedonlywithtry-catchblock.Sinceexceptionhalts the process of execution, we
might have some resources open that will not get closed, so we can use finally block. finally block gets executed
always, whether exception occurred or not.

classTestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerExceptione)
{
System.out.println(e);
}
finally
{
System.out.println("finallyblockisalwaysexecuted");
}
System.out.println("restofthecode...");
}
}

Warning:finally block is always executed


Exception in thread main java.lang.Arithmetic Exception: byzero

III- Semester Object Oriented Programming with JAVA(BCS306A) 9


RV Institute of Technology and Management®

d) Java throws keyword


The Java throws keyword issued to declare an exception. It gives an information to
the programmer that here may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as Null Pointer Exception, it is programmers ‘fault that he is
not performing checkup before the code is used.

throws–Whenwearethrowinganyexceptioninamethodandnothandlingit,thenweneed to use
throws keyword in method signature to let caller program knows the exceptions that
mightbethrownbythemethod.Thecallermethodmighthandletheseexceptionsorpropagate it to
its caller method using throws keyword. We can provide multiple exceptions in the throws
clause and it can be used with main () method also.

Syntaxof java throws


return_typemethod_name()throwsexception_class_name
{
//methodcode
}

throw–
We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them.Sometime we might want to generate exception
explicitly in our code, for example in a user authentication program we should throw
exception to client if the password is null. throw keyword is used to throw exception to the
runtime to handle it.

importjava.io.*;
class M
{
voidmethod()throwsIOException
{
thrownewIOException("deviceerror");
}
}
classTestthrows4
{
publicstaticvoidmain(Stringargs[])throws IOException
{
Mm=newM();
m.method();
System.out.println("normalflow...");
}
}

Warning:Exceptioninthread"main"java.io.IOException:deviceerror

III- Semester Object Oriented Programming with JAVA(BCS306A) 10


RV Institute of Technology and Management®

Final Class, Final methods &Final variables:


a) Final methods:
While method overriding is one of Java’s most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration. Methods declared as final cannot
be overridden.

The following fragment

illustrates final:classBike
{
finalvoid run()
{
System.out.println("running");
}
}

classHondaextends Bike
{
voidrun()
{
System.out.println("runningsafelywith100kmph");
}
public static void
main(Stringargs[]){Honda
honda= new Honda();
honda.run();
}
}
Warning:Complie Time Error as Finalmethods cannot be overridden

b) Final Class:
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final,
too. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations. Here is an example of a final class:

finalclassBike{}
classHonda1extendsBike{
voidrun(){System.out.println("runningsafelywith100kmph");}
publicstaticvoidmain(Stringargs[])
{Honda1honda=newHonda();
honda.run();
}
}
Warning:CompileTimeError

III- Semester Object Oriented Programming with JAVA(BCS306A) 11


RV Institute of Technology and Management®

c) Final variable
If you make any variable as final, you cannot change the value of finalvariable (It will be
constant).

Class Bike
{
finalintspeedlimit=90;//final
variablevoid run()
{
speedlimit=400;
}
public static void main(String
args[]){Bike9obj=newBike9();
obj.run();//CompileTimeError
}
}

Output: Compile Time Error

Creating Your Own Exception Subclasses

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.

1. class InvalidAgeException extends Exception


2. {
3. public InvalidAgeException (String str)
4. {
5. // calling the constructor of parent Exception
6. super(str);
7. }
8. }
9.
10. // class that uses custom exception InvalidAgeException
11. public class TestCustomException1
12. {
III- Semester Object Oriented Programming with JAVA(BCS306A) 12
RV Institute of Technology and Management®

13.
14. // method to check the age
15. static void validate (int age) throws InvalidAgeException{
16. if(age < 18){
17.
18. // throw an object of user defined exception
19. throw new InvalidAgeException("age is not valid to vote");
20. }
21. else {
22. System.out.println("welcome to vote");
23. }
24. }
25.
26. // main method
27. public static void main(String args[])
28. {
29. try
30. {
31. // calling the method
32. validate(13);
33. }
34. catch (InvalidAgeException ex)
35. {
36. System.out.println("Caught the exception");
37.
38. // printing the message from InvalidAgeException object
39. System.out.println("Exception occured: " + ex);
40. }
41.
42. System.out.println("rest of the code...");
43. }
44. }

CHAINED EXCEPTION

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.

III- Semester Object Oriented Programming with JAVA(BCS306A) 13


RV Institute of Technology and Management®

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.

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:

public class ChainedExceptionExample {

public static void main(String[] args) {

try {

String s = null;

int num = Integer.parseInt(s); // the line will throw a NumberFormatException

} catch (NumberFormatException e) {

// create a new RuntimeException with the message "Exception."

RuntimeException ex = new RuntimeException("Exception");

// set the cause of the new Exception to a new NullPointerException with the message " It is actua
l cause of the exception "

ex.initCause(new NullPointerException("It is actual cause of the exception"));

// throw the new Exception with the chained Exception

throw ex;

}
III- Semester Object Oriented Programming with JAVA(BCS306A) 14
RV Institute of Technology and Management®

Output:

Exception in thread "main" java.lang.RuntimeException: Exception at Chained Exception


Example.main(ChainedExceptionExample.java:7)

Caused by: Java.lang.NullPointerException: It is actual cause of the exception

Example of with and without chained Exception

Without Chained Exception:

Filename: NonChainedExceptionExample.java

// Importing the Scanner class from Java.util package

import java.util.Scanner;

// Creating a public class named NonChainedExceptionExample

public class NonChainedExceptionExample {

// Defining the main method that will be executed when the program runs

public static void main(String[] args) {

// Creating a new Scanner object to read input from the console

Scanner scanner = new Scanner(System.in);

// Asking the user to enter a positive integer

System.out.println("Enter a positive integer: ");

// Reading the input integer from the user

int num = scanner.nextInt();

// Closing the scanner object to free up resources

scanner.close();

try {

// Checking if the input integer is negative and throwing an IllegalArgumentException if it is

III- Semester Object Oriented Programming with JAVA(BCS306A) 15


RV Institute of Technology and Management®

if (num < 0) {

throw new IllegalArgumentException("Number must be positive");

// Dividing 100 by the input integer and storing the result in the variable result

int result = 100 / num;

// Printing the result to the console

System.out.println("Result: " + result);

} catch (IllegalArgumentException e) {

// Catching the IllegalArgumentException and printing an error message with the Exception's message

System.out.println("Invalid input: " + e.getMessage());

} catch (ArithmeticException e) {

// Catching the ArithmeticException and printing an error message for division by zero

System.out.println("Error: division by zero");

Output:

Enter a positive integer: -9

Invalid input: Number must be positive

With Chained Exception:

Filename: ChainedExceptionExample.java

// import the Scanner class to allow user input


import java.util.Scanner;

public class ChainedExceptionExample {


public static void main(String[] args) {

III- Semester Object Oriented Programming with JAVA(BCS306A) 16


RV Institute of Technology and Management®

// create a new Scanner object to read user input from the console
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
// read the user's input as an integer
int num = scanner.nextInt();
scanner.close();
try {
// check if the input number is positive, throw an exception if it's not
if (num < 0) {
throw new IllegalArgumentException("Number must be positive");
}
int result = 100 / num;
System.out.println("Result: " + result);
} catch (IllegalArgumentException e) {
// create a new exception with the original Exception as the cause
throw new RuntimeException("Invalid input", e);
} catch (ArithmeticException e) {
// create a new exception with the original Exception as the cause
throw new RuntimeException("Error: division by zero", e);
}
}
}

Output:

Enter a positive integer: -9


Exception in thread "main" java.lang.RuntimeException: Invalid input at
ChainedExceptionExample.main(ChainedExceptionExample.java:17)
Caused by: Java.lang.IllegalArgumentException: Number must be positive at
ChainedException

III- Semester Object Oriented Programming with JAVA(BCS306A) 17

You might also like