0% found this document useful (0 votes)
11 views45 pages

Understanding Java Packages and Exceptions

The document provides an overview of Java packages, including their purpose, access modifiers, and methods for accessing packages from other packages. It also covers exception handling in Java, detailing checked and unchecked exceptions, keywords for handling exceptions, and examples of using try-catch blocks. Additionally, it discusses custom exceptions, nested try statements, and the differences between 'throw' and 'throws' keywords.

Uploaded by

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

Understanding Java Packages and Exceptions

The document provides an overview of Java packages, including their purpose, access modifiers, and methods for accessing packages from other packages. It also covers exception handling in Java, detailing checked and unchecked exceptions, keywords for handling exceptions, and examples of using try-catch blocks. Additionally, it discusses custom exceptions, nested try statements, and the differences between 'throw' and 'throws' keywords.

Uploaded by

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

Module-4

Java Packages
A package in Java is used to group related classes. Think of it as a folder in a file
directory.
Private Protected Default
Public

Inside the same class Yes Yes Yes Yes

Inside the same


package and in a Yes No Yes Yes
subclass
Inside the same
package but not in a Yes No Yes Yes
subclass.
Inside different
packages but in a Yes No Yes No
subclass

Inside different
packages and not in a Yes No No No
subclass.
How to access package from another
package?
•There are three ways to access the package from outside the
package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using
packagename.*
•If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
•The import keyword is used to make the classes and interface
of another package accessible to the current package.
//save by [Link] package mypack;
package pack; import pack.*;
public class A{
public void msg(){ class B{
[Link]("Hello"); public static void main(String args[]){
} A obj = new A();
} [Link]();
}
}
2) Using
[Link]
•If you import [Link] then only declared class of
this package will be accessible.

//save by [Link] package mypack;


package pack; import pack.A;
public class A{ class B{
public void msg(){ public static void main(String args[]){
[Link]("Hello"); A obj = new A();
} [Link]();
} }
}
3) Using fully qualified
name
•If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But
you need to use fully qualified name every time when you are
accessing the class or interface.

package pack; package mypack;


public class class B{
A{ public void public static void main(String args[]){
msg(){ pack.A obj = new pack.A();
[Link]( //using fully qualified name
"Hello");} [Link]();
} }
}
Advantages of Using Java Packages
•Implementing Data Encapsulation in Java is easy with the help of
packages.
•Packages help prevent naming conflicts.
•It orders the classes according to their functions. Hence it is easy to
search for classes.
•You can control the accessibility of the classes by using access
specifiers and packages together.
Built-in
1. [Link] – This package consists of classes that help in performing input out
operations in the program. It also contains language support for data types and
math operations. Whenever you create a class, this package is automatically
imported.
2. [Link] – This package contains classes that specialize in input and output
operations only. One popular thing class you might have seen in programs is the
InputStreamReader class and the BufferedReader
class.
[Link] – This class contains basic utilities that can be useful
while implementing LinkedLists, Trees, HashMaps, and so on. It also has a Scanner
class for input-output operations to the program. It also contains support for date
and time.
4. [Link] – This package contains necessary classes for creating
applets.
[Link] – This package specializes in providing support for designing
GUI elements in
Java.
[Link] – This package contains classes which help in performing
network operations.
class A{ package pack;
private int data=40; public class A{
private void msg(){ protected void msg()
[Link]("Hello java");} {
} [Link]("Hello");}
}
public class Simple{
public static void main(String args[]){
A obj=new A(); package mypack;
[Link]([Link]); import pack.*;
//Compile Time Error
[Link]();//Compile Time Error class B extends A{
} public static void main(String args[]){
} B obj = new B();
[Link]();
}
}

PRIVATE PROTECTED
[Link] 1;
Exceptions 2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Exceptio
ns
•An exception is any abnormal condition arising during the execution of
the program.
•an exception is an event that disrupts the normal flow of the program

•A widely known exception is the division by zero which is an


Arithmetic Exception error.
•All errors and exceptions come under the throwable class in Java. The
throwable class has two subclasses:
• a. Exceptions (Ex: file not found)
b. Error (Ex:out of memory- Non recoverable)
•Examples:
• 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
Checked Exception in Java
• Checked Exception is also known as compile-time exceptions because
it occurs at the compile time.
If there is some code within a method which throws a checked
exception, we must catch it in the same method or we have to
propagate it to the caller using throws keyword.

•which directly inherit from the Throwable class


•For example IOException, SQLException, File
NotFoundException etc.
Unchecked Exception in Java
• Unchecked Exception is also known as Runtime Exceptions because it occurs
at Runtime. This kind of exception occurs at the time of execution. In C++,
all exceptions are unchecked, so it is not forced by the compiler to either
handle or specify the exception. It totally depends upon the programmer
to catch the exceptions.
•The exception classes inheriting the RuntimeException class
•For example:
ArithmeticException,
NullPointerException,ArrayIndexOutOfBoundsException etc.
Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes,
•try
•catch
•finally
•throw
•throws
1. try: The try block is the block where the block of code that is needed to
be checked for exceptions is placed. The try block is followed by a catch
or finally block, it cannot stand alone.

[Link]: Using the catch block we can catch the exception thrown by the
try block. It is declared after the try block.

[Link]: Using the finally block we can execute an important piece of


code because the finally block will be executed regardless of what the
outcome is from the try block.

4. throw: Using the throw keyword we can throw a predefined exception.

[Link]: Using the throws keyword we can declare a new exception


from the exception classes.
Java Exception
Methods:
SL. No. Method Description

This method returns a string message explaining the


1 public String getMessage() exception that occurred.

This method throws the cause of the occurred


2 public Throwable getCause() exception.

This method returns the message of the


3 public String toString() getMessage() method along with the class of
exception concatenated to it.

This method returns the output of the toString()


4 public void printStackTrace() method along with its stack trace

This method returns an array containing all the


5 public StackTraceElement [] getStackTrace() elements of the stack trace.
Syntax
•try {
•//code where exceptions may occur
•}
•catch(Exception e) {
•//Code to handle the exception
•}
Java Finally Block
•The “finally” block follows the try block or the catch block. This
segment houses the code which gets executed whether an
exception occurs or not. This may contain a cleanup code that
you want to execute after the protected block.
• The syntax is as follows:
finally {
//cleanup code
}
public class Main { public class Main {
public static void main(String[ ] args) { public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3}; try {
[Link](myNumbers[10]); / int[] myNumbers = {1, 2, 3};
/ error! [Link](myNumbers[10]);
} }
} catch (Exception e) {
[Link](„Array OutofIndex
Bound.");
}
}
}

O/P: O/P:
ception in thread "main" Array OutofIndex Bound.
[Link]: Index
100 out of bounds for length 50
at [Link]([Link])
class Excp class Excp
{ {
public static void main(String args[]) public static void main(String args[])
{ {
int a,b,c; int a,b,c;
{ try
a=0; {
b=10; a=0;
c=b/a; b=10;
[Link](c); c=b/a;
[Link]("Thank you"); [Link]("This line will not be executed");
}
} catch(ArithmeticException e)
} {
[Link]("Divided by zero");
}
[Link]("After exception is handled");
}
}
Multiple try-catch
•try {
•//Code where exception can occur
•}
•catch(ExceptionTypeA e1) {
•//code that executes if Exception of type A occurs
•}
•catch(ExceptionTypeB e2) {
•//code that executes if Exception of type B occurs.
•}
Multiple try-
catch
import [Link]. * ; catch(ArithmeticException e) {
public class MultCatch { [Link]("You are trying to divide by zero! That
public static void main(String[] args) throws IOException { is not right!");
try { }
int arr[] = {1,3,4,2,45,6}; catch(ArrayIndexOutOfBoundsException e) {
[Link](arr[131]); [Link]("You are trying to access an index not
[Link](25 / 0); in the array!");
[Link]("This statement will never get }
executed because the control has shifted to the catch finally {
block. "); [Link]("This code is in the finally block. It
} does not depend on whether an exception occurs or not.
");
}
}
}
Java throws keyword
•It is used to indicate that an exception can be thrown by a function during
execution.
•On the other hand the throws keyword is useful in case of checked
exceptions.
• If a method performs a particular function that may result in one of the
checked exceptions, the throws keyword is added after the method
declaration..
•Syntax of java throws
return_type method_name() throws exception_class_name
{
//method code
}
public class sample{
int divison(int a, int b) throws
ArithmeticException{ int intet = a/b;
return intet;
}
public static void main(String args[])
{ sample obj = new sample();
try{
[Link]([Link](15,0
));
}
catch(ArithmeticException e){
[Link]("Division
cannot be done using
ZERO");
}
}
}
throw
The throw keyword explicitly throws Exceptions from a method or a
block of code. Generally “throw” keyword helps to throw custom
exceptions.
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.

•Throw instance();
void Votingage(int age){
if(age<18)
throw new ArithmeticException("you can't vote as not Eligible to
vote"); else
[Link]("Eligible for voting");
}
throw
public class TestThrow { public static void main(String[] args)
{ TestThrow obj = new TestThrow();
public static void checkNum(int num) {
if (num < 1) { [Link](-3);
throw new ArithmeticException("\nNumber is negative, cannot calculate sq [Link]("Rest of the code..");
uare");
}
}
else {
[Link]("Square of " + num + " is " + (num*num));
}
}

}
Java throw example
void m()
{
throw new ArithmeticException("sorry");
}
Java throws example
void m()throws ArithmeticException
{
//method code
}
Java throw and throws example
void m() throws ArithmeticException
{
throw new ArithmeticException("sorry");
}
No. throw throws

1) Java throw keyword is used Java throws keyword is used to declare


to explicitly throw an exception. an exception.

2) Checked exception cannot Checked exception can be propagated


be propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the


method signature.
5) You cannot throw You can declare multiple
multiple exceptions. exceptions e.g.
public void
method()throws
IOException,SQLException.
throws
import [Link].*; public static void main(String[] args)
class Main { { try{
public static findFile();
void findFile() }
throws catch(IOException e)
IOException { { [Link](e
// code that may produce IOException );
File newFile=new File("[Link]"); }
FileInputStream stream=new }
FileInputStream(newFile); }
}
public static void writeToFile() throws public static void main(String[] args)
IOException { {
try {
BufferedWriter bw = new BufferedWriter(new writeToFile();
FileWriter("[Link]")); }
[Link]("Test");
[Link](); catch (IOException e) {
} [Link]();
}
}
•Create a custom exceptions in Java for bank class.
class InsufficientBalanceException extends Exception Class bank{
{ Int balance= 2000;
public InsufficientBalanceException(String message) public void withdraw(double amount) throws
{ InsufficientBalanceException
super(message); {
} if (balance - amount < 1000) {
} throw new InsufficientBalanceException("Insufficient
balance. Minimum balance of 1000 required.");
}
balance -= amount;
[Link]("Withdrawn: " + amount);
}
}
public class Main{
public static void main(String[] args) {
[Link]("Hello World");
bank b = new bank();
try{
[Link](30000);
}
catch(Exception e)
{ [Link]([Link]())
;
}
}}
Nested try statements
Nested try statements in Java are try blocks within another try
block. These are useful when a piece of code inside a try block
may itself throw exceptions that you want to handle specifically .

How It Works:

• The outer try-catch handles exceptions from the outer code.

• The inner try-catch focuses on exceptions within the nested try


block.

• If an exception occurs in the inner try block that is not handled


by its corresponding catch block, the exception is propagated
to the outer try-catch.
public class NestedTryExample {
public static void main(String[] args) {
try {
// Outer try block
[Link]("Outer try block started.");

try {
// Inner try block
[Link]("Inner try block started.");

int[] numbers = {1, 2, 3};


[Link](numbers[5]); // This will throw
ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught ArrayIndexOutOfBoundsException in
inner catch block: " + [Link]());
}
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Caught ArithmeticException in outer catch
block: " + [Link]());
} finally {
[Link]("Finally block executed (Outer).");
}
}
Output
Outer try block started.
Inner try block started.
Caught ArrayIndexOutOfBoundsException in inner catch block:
Index 5 out of bounds for length 3
Caught ArithmeticException in outer catch block: / by zero
Finally block executed (Outer).
public class NestedTryPropagationExample {
public static void main(String[] args) {
try {
// Outer try block
[Link]("Outer try block started.");

try {
// Inner try block
[Link]("Inner try block started.");

int[] numbers = {1, 2, 3};


[Link](numbers[5]); // This will throw ArrayIndexOutOfBoundsException

} catch (ArithmeticException e) {
// This catch block does NOT handle ArrayIndexOutOfBoundsException
[Link]("Caught ArithmeticException in inner catch block: " +
[Link]());
}

} catch (ArrayIndexOutOfBoundsException e) {
// Outer catch block handles the unhandled exception from the inner try block
[Link]("Caught ArrayIndexOutOfBoundsException in outer catch block: " +
[Link]());
} finally {
[Link]("Finally block executed (Outer).");
}
}
Chained exceptions
Chained exceptions in Java allow an exception to be linked to another exception. This
means that when an exception occurs, it can signify a problem that resulted from
another exception, providing clearer contextual information about the issue. This is
particularly useful when dealing with layers of APIs or components where one might
throw an exception based on another lower-level exception.
public class ChainedExceptionsDemo {
static void methodD() {
public static void main(String[] args) {
boolean conditionFalse = true; // Simulate a
try {
condition that causes an exception
methodC();
if (conditionFalse) {
} catch (Exception e) {
throw new
[Link]();
IllegalArgumentException("Invalid argument
}
passed to methodD");
}
}
}
static void methodC() throws Exception {
}
try {
methodD();
} catch (IllegalArgumentException e) {
throw new Exception("Error in methodC:
Illegal argument provided", e);
}
}

You might also like