Unit 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

UNIT-IV

PACKAGES: Packages, Different Types of Packages, Access Protection, Importing Packages.


EXCEPTION HANDLING: Exception-handling fundamentals, throw Clause, throws Clause,
Types of Exceptions: Built-in Exception, User Defined Exception.

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.Here, we will have the
detailed learning of creating and using user-defined packages.

Advantages of Java Package


1) Java 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:

Create a directory with name “mypack” and write these files

A.java

package mypack;

public class A
{
public void displayA()
{
System.out.println("I A M IN CLASS A");
}
}

B.java

package mypack;

public class B
{
public void displayB()
{
System.out.println("I A M IN CLASS B");
}
}
Compile

javac A.java

javac B.java

/* move to parent directory and write these files. */

Demo.java

import mypack.*;

class Demo
{
public static void main(String args[])
{

A obj=new A();
obj.displayA();

}
}

Compile
javac Demo.java
java Demo

output:
I A M IN CLASS A

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.

Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.
Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.

package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple

OUTPUT:
Hello subpackage

Set CLASSPATH System Variable:

To set the CLASSPATH variable:

In Windows -> set CLASSPATH=C:\users\java\classes

Access Protection

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.
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 modifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories. While Java’s access control mechanism
may seem complicated, we can simplify it as follows. Anything declared public can be accessed
from anywhere. Anything declared private cannot be seen outside of its class. When a member
does not have an explicit access specification, it is visible to subclasses as well as to other classes
in the same package. This is the default access. If you want to allow an element to be seen
outside your current package, but only to classes that subclass your class directly, then declare
that element protected.
Importing Packages

In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the
import statement:

import pkg1 [.pkg2].(classname | *);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.). There is no practical limit on the depth of a
package hierarchy, except that imposed by the file system. Finally, you specify either an explicit
classname or a star (*), which indicates that the Java compiler should import the entire package.
This code fragment shows both forms in use:

import java.util.Date;
import java.io.*;

EXCEPTION HANDLING

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, below given are some scenarios where
exception occurs.

 A user has entered 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.
Based on these we have three categories of Exceptions you need to understand them to know
how exception handling works in Java

Checked exceptions: A checked exception is an exception that occurs at the compile time, these
are also called as compile time exceptions. These exceptions cannot simply be ignored at the
time of compilation, the Programmer should take care of (handle) these exceptions.

For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then an FileNotFoundException occurs, and compiler
prompts the programmer to handle the exception.

import java.io.File;
import java.io.FileReader;

public class FilenotFound_Demo {

public static void main(String args[]){


File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}

If you try to compile the above program you will get exceptions as shown below.

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

Some of the examples of checked exceptions


Unchecked exceptions: An Unchecked exception is an exception that occurs at the time of
execution, these are also called as Runtime Exceptions, these include programming bugs, such as
logic errors or improper use of an API. runtime exceptions are ignored at the time of
compilation.

For example, if you have declared an array of size 5 in your program, and trying to call the 6th
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

public class Unchecked_Demo {

public static void main(String args[]){


int num[]={1,2,3,4};
System.out.println(num[5]);
}

If you compile and execute the above program you will get exception as shown below.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5


at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Java exception handling is managed via five keywords: try, catch, throw, throws,and finally.

This is the general form of an exception-handling block:

try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...

finally {
// block of code to be executed before try block ends
}

Some of examples of unchecked exceptions

USING TRY AND CATCH

To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch. To illustrate how easily this can be done, the following
program includes a try block and a catch clause which processes the Arithmetic Exception
generated by the division-by-zero error:

class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

This program generates the following output:


Division by zero.
After catch statement.

MULTIPLE CATCH CLAUSES

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. The following
example traps two different exception types:

// Demonstrate multiple catch statements.

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 oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

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 the entire nested try statements are exhausted. If no catch
statement matches, then the Java run-time system will handle the exception. Here is an example
that uses nested try statements:

// An example of nested try statements.


class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

OUTPUT:

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One


a=1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One Two


a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
THROW

So far, you have only been catching exceptions that are thrown by the Java run-time system.
However, 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.


Simple 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 into a catch clause, or creating one with the new operator.

Here is a sample program that creates and throws an exception. The handler that
catches the exception rethrows it to the outer handler.

// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

This program gets two chances to deal with the same error. First, main( ) sets up an exception
context and then calls demoproc( ). The demoproc( ) method then sets up another exception-
handling context and immediately throws a new instance of NullPointerException, which is
caught on the next line. The exception is then rethrown. Here is the resulting output:

Caught inside demoproc.


Recaught: java.lang.NullPointerException: demo
THROWS
If a method is capable of causing 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 the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}

EXAMPLE:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
OUTPUT

inside throwOne
caught java.lang.IllegalAccessException: demo

DIFFERENCE BETWEEN THROW AND THROWS IN JAVA

S.No throw throws


1) Java throw keyword is used to Java throws keyword is used to declare an
explicitly throw an exception. exception.
2) Checked exception cannot be Checked exception can be propagated with
propagated using throw only. 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 multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
FINALLY

finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the 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.

EXAMPLE:

// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
OUTPUT:

inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally

Java’s Built-in Exceptions

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy