Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Module 4(OOPs With Java) 1

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

Module 4(OOPs With Java) 1

Ppt
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

MODULE-4

Chapter-1 Packages
Creating & Accessing a package
Consider the following program that illustrates the creating and accessing packages
package com.oops.example;
public class A{
int x;
public void putData(int x){
this.x = x;
}
public void getData( ){
System.out.println(“The Value of x is: ” + x);
}
}
 The above program contains a class A written within a package com.oops.example and
contains two methods namely putData(int x) and getData() which assigns the value of instance
variable x and retrieves the value of x respectively.
Importing a package
package com.oops.example;
public class A{
int x;
public void putData(int x){
this.x = x;
}
public void getData( ){
System.out.println(“The Value of x is: ” + x);
}
}
Conitn….
 The members of class A that is present in one particular package can be accessed by class B present
in another package by importing the class A’s package using the keyword ‘import’
immediately after the package statement in class B.

 There are two ways of accessing the classes stored in the core package
 Suppose that we want to use the ‘Date’ class present in the package java.util, then we can import the
statement in the program written as
import java.util.Date;
 There may be a situation in which we want to make use of several classes present in a package, then we import the
statement in the program written as

import java.util.*;
Here * indicates any class in the corresponding package.
Packages and member access:
 The effect of access specifiers over different conditions in packages are as listed below,

• Public mode of members is accessible among all the


classes, subclasses and nonsubclasses present in same
package or different package.
• Whereas, protected mode of members is accessible
among all the classes, subclasses and non-subclasses in the
same package along with subclasses in different package.
But is not accessible to non-subclasses present in different
package.
• The default mode of members is accessible to all classes,
subclasses and non-subclasses in the same package. But is
not accessible to the classes, subclasses and non-subclasses
present in the different package.
• The private mode of members is accessible to only the
class that declared it, and is not accessible to subclasses and
non-subclasses in the same package or in different package.
PACKAGES
 Packagesare containers for classes that are used to keep the class namespace
compartmentalized.
 Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions.
 Creating a package in Java is done by using the keyword ‘package’ at the beginning of the
program.
Syntax: package package_name;
 This package statement defines the namespace in which the classes are stored. If we omit

the package statement, then the classes are put into a default package which has no name.
 The package name has to be specified in lowercase letters where multiple words is separated
by dot is the convention used to define a package name.
e.g., package com.oops.example
 The package statement is going to create a directory structure to store the class. That is, a
directory structure of the form \com\oops\example\ gets created for the above example,within
which the classes will be defined.
MODULE-4
Chapter-2 Exception Handling
SYLLABUS

 Exception Handling Fundamentals

 Exception Types

 Uncaught Exceptions

 Using try and catch

 Multiple Catches

 Use of throw, throws and finally

 Java’s In-Built Exception

 Nested try statements

 Creating Your Own Exception Subclasses

 Chained Exceptions
EXCEPTION HANDLING FUNDAMENTALS:
 An exception is an abnormal condition that arises in a code sequence at runtime.
 In other words, an exception is a runtime error.
 In Java, whenever an exceptional condition arises, an exception object is created
by the Java Runtime Environment automatically.
 Java’s exception handling is managed using 5 keywords namely, try, catch, throw,
throws and finally.
 Such program statements that have to be monitored for an exception must be
placed within try-block, then the corresponding object is created by the JRE and
thrown, which can be caught using the catch-block.
 To manually throw an exception, the keyword ‘throw’ must be used.
 If an exception is thrown out of a method, then the ‘throws’ clause must be used.
 Any critical code that has to be executed after a try block completes must be put
inside the ‘finally’block.
EXCEPTION TYPES:

There are always some problems that arise during the run-time of a program.
These problems can be classified into 2 types namely,
1. Exceptions (which can be handled)
2. Errors (which cannot be handled)
All exceptions are sub-classes of the class Exception. All errors are sub-classes
of class Error. Both Exception and Error are sub-classes of class Throwable. The
inheritance hierarchy is as shown below,
UNCAUGHT EXCEPTIONS:

 Upon execution of the above program, a Division by Zero exception would occur and hence the JRE
would dynamically create an object of the class ArithmeticException and throws this exception object.
This exception object ideally must be caught by the catch block given by the programmer.
 Suppose, if a catch block is not given, then the object by default would be handled by the default
exception handler provided by the Java Runtime System. This is the reason why the application never
crashes in case of Java.
 The default handler handles the exception by printing the type of exception and the point at which
exception occurred (called as stack trace) as,
Java.lang.ArithmeticException: / by Zero
at Example.main(Example.java:4)
USING TRY AND CATCH:

 The try and catch blocks must be used by the programmer to handle
exceptions.

The benefits of using try-catch block are-


 The program will not terminate.
 Retains the control within the program.
 Fix the problem.
MULTIPLE CATCHES:
 Multiple catch blocks would be required, where a single piece of code would be generating more than
one type of exception.
 To handle such exceptions, the programmers must specify 2 or more catch blocks each catching a
different kind of exception.
NESTED TRY STATEMENTS:

 The try statement can be inside the block of another try statement.
 Each time a try statement is entered, the context of that exception is pushed on
the stack.
 If an inner try statement doesn’t have a catch handler for a particular
exception, the stack unwound and the next try statements catch handlers are
inspected for a match. If no catch statement matches, then the Java run-time
system will handle the exception.
USE OF THROW, THROWS AND FINALLY:

 Not only the Java Runtime Environment generates and throws a exception automatically, it is also
possible for a program to throw an exception explicitly using the “throw” keyword.
 The general form of throw is:

Throw ThrowableInstance;
 Here, ThrowableInstance is an object of type Throwable.
 There are two ways to obtain a Throwable object:
 Using a parameter in a catch clause
 Creating one with the new operator

 The flow of execution stops immediately after the throw statement. Any subsequent statements are not
executed.
 The nearest enclosing try block is inspected to see if it has any catch statement that matches the type of
exception.
 If no matching catch is found , then the default exception handler halts the program and prints the stack
trace.
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);
}
}
}
THROWS

 If a method is causing an exception, then this behaviour can be specified


with the help of throws clause in the method declaration.
 A throws clause lists the types of exceptions that a method mightmthrow.
This is necessary for all exceptions, except those of type Erroror
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 method declaration that include a throws clause:

 Here, exception list is a comma-separated list of the exceptions that a


method can throw.
FINALLY
 The finally block in Java is a crucial part of exception handling.
 It is used to execute important code such as closing resources, regardless of
whether an exception is thrown or not.
 The finally block always executes when the try block exits, ensuring that
cleanup code runs.
 “finally” creates a block which would get executed irrespective of the try block
generating or not generating an exception.
 Even if a return statement is given inside the try block or catch block, finally
would still definitely execute. Only System.exit(0) method can stop the
execution of finally block.
JAVA’S IN-BUILT EXCEPTIONS:

There are basically 2 types of exceptions namely,


 Unchecked Exceptions: are such exceptions where the Java compiler doesn’t check to see if
any method throws or handles the exception.
 Checked Exceptions: are such exceptions where the java compiler checks to see if any method throws or
handles these exceptions.
CONTIN…
CREATING YOUR OWN EXCEPTION SUBCLASSES:

 We can create our own exception types to handle situations specific to the applications.

 This can be done by creating a subclass of exception class Throwable class.

 This exception class does not define the methods of its own , inherits those methods provided by
throwable.
 Exception defines four constructors, two support chained exceptions and the other two are shown here.

1.Exception()
2.Exception(String msg)
 The first form creates an exception that has no description.

 The second form specify description of the exception. Although specifying a description when an
exception is created is often useful, sometimes it is better to override toString( ).
CHAINED EXCEPTIONS:
 The chained exception feature allows you to associate another exception with an exception.

 This second exception describes the cause of the first exception.

 To allow chained exceptions, two constructors and two methods were added to Throwable. The
constructors are shown here:
• Throwable(Throwable causeExc)
• Throwable(String msg, Throwable causeExc)
 In the first form, causeExc is the exception that causes the current exception. That is, causeExc is the
underlying reason that an exception occurred.
 The second form allows you to specify a description at the same time that you specify a cause exception.

 These two constructors have also been added to the Error, Exception, and RuntimeException classes.

 The chained exception methods added to the throwable are getCause() and initCause().

 The getCause() method returns the exception that underlies the current exception.

 If there is no underlying exception , null is returned.

 The initCause() method associates causeExc with the invoking exception and returns a reference to the
exception.

You might also like