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

Module 4

Module-4 covers Java packages and exception handling, detailing the structure and access levels of packages, as well as the fundamentals of exception handling using keywords like try, catch, throw, throws, and finally. It explains how to create and import packages, manage exceptions through various catch clauses, and the significance of the Throwable class. Additionally, it discusses the implications of uncaught exceptions and the use of nested try statements for better error management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module 4

Module-4 covers Java packages and exception handling, detailing the structure and access levels of packages, as well as the fundamentals of exception handling using keywords like try, catch, throw, throws, and finally. It explains how to create and import packages, manage exceptions through various catch clauses, and the significance of the Throwable class. Additionally, it discusses the implications of uncaught exceptions and the use of nested try statements for better error management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Module-4

Packages and Exception Handling

By:
Prof. Kavitha B
Asst.Prof ,Dept ISE
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
 A java package is a group of similar types of classes,
interfaces and sub-packages.
 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.
 All classes in Java belong to some package. When no
package has been explicitly specified, the default (or
global) package is used.
 To create a package, you will use the package
statement.
 General form of the package statement is
package pkg;
 Here pkg is the name of the package.
 More than one file can include the same package
statement.
 You can create hierarchy of packages.
 The general form is
package pack1.pack2.pack3…..packN;
Ex:
package alpha.beta.gamma;
 must be stored in /alpha/beta/gamma specifies
the path to be specified directories.
 Ex:
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
 If you want to keep the package within the same
directory, you can use . (dot).
 To compile: javac -d directory javafilename
 To Run: java packagename.Simple
 For above program
to complile: javac –d . Simple.java
to run: java mypack.Simple
 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.
 Because of the interplay between classes and
packages, 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.

 The three access specifiers, private, public, and


protected, provide a variety of ways to produce the
many levels of access required by these categories.
 Class member access
Private No modifier Protected Public
or default
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

having default access modifier are accessible only within the same package.
protected access modifier
 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.
 Ex:
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Default
 If you don't use any modifier, it is treated as default by
default.
 The default modifier is accessible only within package.
It cannot be accessed from outside the package.
 It provides more accessibility than private. But, it is more
restrictive than protected, and public.
EX:
package pack;
class A //save by A.java
{
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();//Compile Time Error
obj.msg();//Compile Time Error
}
}
 Here,the scope of class A and its method msg() is default
so it cannot be accessed from outside the package
Importing packages
 Using import, you can bring one or more members of a
package into view.
 The general form of import statement.
import pkg.classname;
 Here pkg is the name of the package, which can
include its full path, and classname is the name of the
class being imported.
 If you want to import the entire contents of a package,
use an asterisk(*) for the class name.
 Ex:
 import mypack.MyClass;
 import mypack.*;
 In the first case,the MyClass is imported from mypack.
 In the second,all of the classes in myback are
imported.
EX:
import java.util.Date;
import java.io.*;
 All of 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.
import java.lang.*;
EX:
import java.util.*;
class MyDate extends Date {}

 The same example without the import statement


looks like this:
class MyDate extends java.util.Date {}
 Importing java’s Standard Packages
 Java defines a large number of standard classes that
are available to all programs.

Subpacka Description
ge
java.lang Contains a large number of general-purpose classes
java.io Contains the I/O classes
java.net Contains those classes that support networking
java.Applet Contains classes for creating applets
java.awt Contains classes that support the Abstract Window
Toolkit
java.util Contains various utility classes, plus the Collections
Framework.
 How to access package from another package?
 There are three ways to access the package from
outside the package.
import package.*;
import package.classname;
fully qualified name.
package pack18; // packagename.*
public class raghu18
{
public void msg()
{
System.out.println("Hello rnsit");
}
}
------------------------------------------------------
package mypack12;
import pack18.*;
class prasad12
{
public static void main(String args[])
{
raghu18 obj = new raghu18();
obj.msg();
}
}
//save by A.java Using packagename.classname

package pack;
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();
}
}
//save by A.java Using fully qualified name
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
name
obj.msg();
}
}
Exception Handling
 The exception hierarchy:
 An exception is an error that occurs at run time.
 In java, all exceptions are represented by classes.
 All exception class are derived from a class called
Throwable.
 Throwable class is the superclass of all exceptions
in the Java language.
 When an exception occurs in a program, an object of
some type of exception class is generated.
Exception handling fundamentals
 Java exception handling is managed via five
keywords.
 They are try, catch, throw, throws and finally.
 Programs statements that you want to monitor for
exceptions are contained a try block.
 If an exception occurs within the try block, it is
thrown.
 Your code can catch this exception using catch and
handle it in some rational manner.
 System-generated exceptions are automatically
thrown by the java run-time system.
 To manually throw an exception, use the keyword
throw.
 Java try block must be followed by either catch or
finally block.
 In some cases, an exception that is thrown out of a
method must be specified as such by a throws clause.
 Any code that absolutely must be executed upon exiting
from a try block is put in a finally block.
 Syntax of java try-catch
try
{
//code that may throw exception
}catch(Exception_class_Name ref){}
 Syntax of try-finally block
try
{
//code that may throw exception
}
finally{}
 Ex:
 Without using try-catch(Uncaught Exceptions)
public class testtry
{
public static void main(String args[])
{
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
 Output:
 Exception in thread main
java.lang.ArithmeticException:/ by zero
 EX1: Using java try-catch block.(caught Exceptions)
public class testtry1
{
public static void main(String args[])
{
try{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
 Output:
 Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
EX2:
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.");
}
}
The consequences of an uncaught
exception
 If your program does not catch an exception, then it
will be caught by the JVM.
 The trouble is that the JVM’s default exception handler
terminates execution and displays an error message
followed by a list of the methods calls that lead to the
exception.
 Internal working of java try-catch block
Multiple catch Clauses
 You can associate more than one catch clause with a
try. Each catch must catch a different type of
exception.
 At a time only one Exception is occurred and at a
time only one catch block is executed.
 Ex:
public class TestMultipleCatch
{
public static void main(String args[])
{
try{
int a[]=new int[5];
a[5]=30;
} Contd….
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
catch(Exception e)
{

System.out.println("common task completed");


}
System.out.println("rest of the code...");
}
}
 All catch blocks must be ordered from most
specific to most general i.e. catch for
ArithmeticException must come before catch for
Exception .
EX:
class TestMultipleCatchBlock1
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30;
}
contd…..
catch(Exception e)
{
System.out.println("common task completed");
}
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
System.out.println("rest of the code...");
}
} OUTPUT
Compile-time error
Nested try Statements
 One try block can be nested within another.
 An exception generated within the inner try block that
is not caught by a catch associated with that try is
propagated to the outer try block.
 Syntax
try
{
statements ;
try
{
statements;
} catch(Exception e) { }
} catch(Exception e) { } ....
 Ex:
public class nestedtryy
{
public static void main(String args[])
{
try
{
try
{
int a[]=new int[5];
a[5]=30;
}
catch(Exception e)
{
System.out.println(“BE");
}
try {
int a[]=new int[5];
a[4]=30/0;
}
catch(ArithmeticException e)
{
System.out.println(“MCA");
}
int b[]=new int[5];
b[5]=30;
}
catch(Exception e)
{
System.out.println(“RNSIT");
}
}
}
throw
 The Java throw keyword is used to explicitly throw
an exception.
 we can throw either checked or unchecked exception
in java by throw keyword.
 The syntax of java throw keyword is given below
throw exceptob;
 Here, exceptob must be an object of an exception
class derived from Throwable.
 Only object of Throwable class or its sub classes
can be thrown.
Contd….
 Creating Instance of Throwable class
 There are two possible ways to get an instance of
class Throwable,
 Using a parameter in catch block.
 Creating instance with new operator.
 new NullPointerException("test");
 This constructs an instance of
NullPointerException with name test.
 Ex:1
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
} OUTPUT
Exception in thread main java.lang.ArithmeticException:not valid
 Ex:2
class Test21{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
avg();
System.out.println("Exception caught");
} }
EX3: rethrow the exception
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside
demoproc.");
throw e; contd…..
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}
Output
 Caught inside demoproc.
 Recaught: java.lang.NullPointerException: demo
throws
 In some cases, if a method generates an exception
that it does not handle, it must declare that exception in
a throws clause.
 The general form of throws is
return-type methName(param-list)throws except-
list
{
//body
}
 Here, except-list is a comma-separated list of
exceptions that the method might throw outside of
itself.
 subclass of Error or RuntimeException don’t need to
be
specified in a throws list.
Ex:1
import java.io.*;
class rns
{
void mca()throws IOException
{
throw new IOException("device error");
}
}
public class Testthrows2
{
public static void main(String args[])
{
Contd…….
try{
rns m=new rns();
m.mca();
}
catch(Exception e)
{
System.out.println(e);
System.out.println("normal flow...");
}
} OUTPUT:
java.io.IOException: device error
normal flow…
EX:2
import java.io.*;
class rnsit
{
void mca(int a) throws IOException,ArithmeticException
{
if(a%2==0)
throw new IOException("device error");
else
throw new ArithmeticException("error");
}
} Contd…..
class Testthrows
{
public static void main(String args[])
{
try
{
rnsit m=new rnsit();
m.mca(2);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("normal flow...");
}
} OUTPUT
java.io.IOException:device Error
normal flow…
EX3:
class ThrowsDemo
{
static void throwOne() throws
IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
contd….
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
output
 inside throwOne
 caught java.lang.IllegalAccessException: demo
finally
 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.
 Java finally block must be followed by try or catch
block.
 Syntax:
finally{
finally code
}
 Ex:1
class TestFinallyBlock
{
public static void main(String args[])
{
try{
int data=25/5;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
 Ex:2
class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
 OUTPUT
 finally block is always executed

 Exception in thread main


java.lang.ArithmeticException:/ by zero

 For each try block there can be zero or more catch


blocks, but only one finally block.
Difference between throw and
throws
throw Throws
Java throw keyword is used to Java throws keyword is used to
explicitly throw an exception. declare an exception.
Throw is followed by an
Throws is followed by class.
instance.
Throw is used within the Throws is used with the
method. method signature.
You can declare multiple
You cannot throw multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
 Difference between final, finally and finalize

final finally Finalize

Final is used to apply


restrictions on class,
Finally is used to place Finalize is used to
method and variable.
important code, it will be perform clean up
Final class can't be
executed whether processing just before
inherited, final method
exception is handled or object is garbage
can't be overridden and
not. collected.
final variable value can't
be changed.

Final is a keyword. Finally is a block. Finalize is a method.


Exception Types
 All exception types are subclasses of the built-in class
Throwable.
 Throwable is at the top of the exception class hierarchy.
 Immediately below Throwable are two subclasses that
partition exceptions into two distinct branches.
 One branch is headed by Exception.
 This class is used for exceptional conditions that user
programs should catch.
 This is also the class that you will subclass to create your
own custom exception types.
 The other branch is topped by Error, which defines
exceptions that are not expected to be caught under
normal circumstances by your program.
Java built-in Exceptions
 Inside the standard package java.lang , Java
defines several exception classes.
 There are two types of exceptions: checked
exceptions and unchecked(Runtime
exceptions) exceptions.
 The main difference between checked and
unchecked exception is that the checked
exceptions are checked at compile-time while
unchecked exceptions are checked at runtime.
Unchecked exceptions defined by
java.lang
Exception Meaning
ArithmeticException Arithmetic error, such as division by
zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast
IllegalArgumentException Illegal argument used to invoke a
method
NullPointerException Invalid use of a null reference
TypeNotPresentException Type not found
NumberFormatException Invalid conversion of a string to a
numeric format
StringIndexOutOfBoundsException Attempt to index outside the bounds of
a string
Checked exceptions defined by
java.lang
Exception Meaning
ClassNotFoundException Class not found
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
ReflectiveOperationException Superclass of reflection-related
exceptions
Creating Exception subclasses or how to create your
own exception

 If you are creating your own Exception that is known as


custom exception or user-defined exception.
 Just define a subclass of Exception(which is a
subclass of Throwable).
 The Exception class does not define any methods of its
own. It does inherit those methods provided by
Throwable.
 You can override one or more of these methods in
exception subclass that you create.
 Two commonly used Exception constructors are shown
here;
Exception()
Exception(String msg)
public class WrongFileNameException extends Exception
{
public WrongFileNameException(String errorMessage)
{
super(errorMessage);
}
}
 We need to write the constructor that takes the String
as the error message and it is called parent class
constructor.
Step1: Extend the Exception Class
public class MyCheckedException extends Exception
{
public MyCheckedException(String message)
{
super(message);
}
}
Step 2. Throw the Exception
public class Example {
public void doSomething(int value) throws MyCheckedException
{
if (value < 0) {
throw new MyCheckedException("Value cannot be negative!");
}
// Other logic
}
}
Step3: Catch the Exception
public class Main {
public static void main(String[] args) {
Example example = new Example();
try {
example.doSomething(-1);
}
catch (MyCheckedException e) {

System.out.println("Caught exception: " + e.getMessage());


}
}
}
Ex:
import java.util.Scanner;

class Eligible extends Exception {


Eligible(String msg) {
super(msg);
}
}

class NotEligible extends RuntimeException {


NotEligible(String msg) {
super(msg);
}
}

Contd…..
class Example {
public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

try {
System.out.println("Enter age: ");
int age = sc.nextInt();

if (age < 18) {


// Throw NotEligible exception if the age is less
than 18
throw new NotEligible("Not eligible for marriage");
}
else if (age > 18) {
// Throw Eligible exception if the age is greater than 18
throw new Eligible("Eligible for marriage");
} else {
// For age == 18, print a thank you message
System.out.println("Thank you");
}
} catch (NotEligible | Eligible e) {
// Catch the custom exceptions and print the message
System.out.println(e.getMessage());
} finally {
// Close the scanner object (good practice to close resources)
sc.close();
}
}
}
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 :
 Throwable(Throwable cause) :- Where cause is
the exception that causes the current exception.
 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 :
 getCause() method :- This method returns actual
cause of an exception.
 initCause(Throwable cause) method :- This
method sets the cause for the calling exception.
public class chain
{
public static void main(String[] args)
{
try
{
NumberFormatException ex =
new
NumberFormatException("Exception");
ex.initCause(new NullPointerException(
"This is actual cause of the exception"));
throw ex;
} contd....
catch(NumberFormatException a)
{
System.out.println(a);
System.out.println(a.getCause());
}
}}
output
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause
of the exception
Example2:
import java.io.IOException;

public class Chain1 {


public static void main(String[] args) {
try {
// Creating an ArithmeticException and chaining another exception (IOException) as
its cause
ArithmeticException ex = new ArithmeticException("Division by zero error");
ex.initCause(new IOException("I/O operation failed, which is the actual cause of the
exception"));

// Throwing the ArithmeticException


throw ex;
} catch (ArithmeticException a) {
// Printing the exception
System.out.println(a);

// Printing the cause of the exception (IOException)


System.out.println("Cause: " + a.getCause());
}
}
}

You might also like