0% found this document useful (0 votes)
26 views30 pages

Chapter 4

The document discusses exception handling in Java. It explains that exceptions are abnormal runtime errors that can be handled through try/catch blocks. The try block contains code that might throw exceptions, while catch blocks handle specific exception types if they occur. This allows the normal flow of a program to continue even if errors happen. The document also covers checked and unchecked exceptions, and how exceptions are represented by objects in a class hierarchy.

Uploaded by

lencho03406
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)
26 views30 pages

Chapter 4

The document discusses exception handling in Java. It explains that exceptions are abnormal runtime errors that can be handled through try/catch blocks. The try block contains code that might throw exceptions, while catch blocks handle specific exception types if they occur. This allows the normal flow of a program to continue even if errors happen. The document also covers checked and unchecked exceptions, and how exceptions are represented by objects in a class hierarchy.

Uploaded by

lencho03406
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
You are on page 1/ 30

Chapter 4: Exception handling

• An exception is an abnormal condition that arises in a code


sequence at run time.

• In other words, an exception is a runtime error.

• In computer languages that do not support exception handling,


errors must be checked and handled manually—typically through
the use of error codes, and so on.

• Java’s exception handling process, brings run-time error


management into the object-oriented world.
1
Exception handling(cont’d…)

• Java exception is an object that describes an exceptional (error)


condition that has occurred in a piece of code.

• When an exceptional condition arises, an object representing that


exception is created and thrown in the method that caused the error.

• That method may choose to handle the exception itself, or pass it on.
Either way, at some point, the exception is caught and processed.

• Exceptions can be generated by the Java run-time system, or they can


be manually generated by your code.
2
Exception handling(cont’d…)

• The Exception Handling in Java is one of the powerful mechanism


to handle the runtime errors so that the normal flow of the
application can be maintained.
• The core advantage of exception handling is to maintain the
normal flow of the application.
• An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions.
• Suppose there are 10 statements in a Java program and an exception
occurs at statement 5; the rest of the code will not be executed.
• However, when we perform exception handling, the rest of the
statements will be executed.

3
Exception handling(cont’d…)

• Exceptions thrown by Java, related to fundamental errors that


violate the rules of the Java language or the constraints of the
Java execution environment.

• Manually generated exceptions are typically used to report


some error condition to the caller of a method.

• Java exception handling is managed by: try, catch, throw,


throws.
4
Exception handling(cont’d…)

• Program statements that you want to monitor for exceptions


are contained within 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 runtime system.
5
Java exception class hierarchy

6
Exception Types

• All exception types are subclasses of the built-in class Throwable.

Thus, 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. 7


Exception Types
• Exceptions of this type are automatically defined for the programs that
you write and include things such as division by zero and invalid array
indexing.

• The other branch is topped by Error, which defines exceptions that are
not expected to be caught under normal circumstances by your
program.

• Exceptions of type Error are used by the Java run-time system to


indicate errors having to do with the run-time environment, itself.
Stack overflow is an example of such an error. 8
Exception Types
• RuntimeException, and its subclasses are known as unchecked exceptions.

• All other exceptions except errors and runtime exception are known as checked

exceptions, meaning that the compiler forces the programmer to check and deal

with them.

• In most cases, unchecked exceptions reflect programming logic errors that are

unrecoverable.
• For example, an IndexOutOfBoundsException is thrown if you access an element in an
array outside the bounds of the array. These are logic errors that should be corrected in the
program.

9
Java’s Unchecked RuntimeException Subclasses

10
Java’s Checked Exceptions

11
Comparing Checked and unchecked Exception

• Checked Exceptions are checked • Unchecked exceptions are just


at compile time. It is handled at opposite to the checked
compile time . exceptions. These exceptions are
not checked and handled at
• Checked Exception are direct compile time.
subclasses of exception but not
extended from • Unchecked exceptions are the
RuntimeException class. direct subclasses of the
RuntimeException class.
• The code gives a compilation
error in the case when a method • The code compiles without any
throws a checked exception. error because the exceptions
escape the notice of the compiler.

12
Checked and unchecked Exception(cont’d…)

• Checked exceptions mostly occur • unchecked exceptions occur


when the probability of failure is mostly due to programming
too high. mistakes.
• Common checked exceptions • Common unchecked exceptions
include IOException,
include ArithmeticException,
DataAccessException,
InterruptedException, etc. NullPointerException, etc.
• checked exceptions are propagated • unchecked exceptions are
using the throws keyword. automatically propagated.

13
Uncaught Exceptions

• This small program includes an expression that


intentionally causes a divide-by-zero error:
class DivByZero{
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
14
Uncaught Exceptions(cont’d…)

• When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception.

• This causes the execution of DivByZero to stop, because once an exception has been
thrown, it must be caught by an exception handler and dealt with immediately.

• In the above example, we haven’t supplied any exception handlers of our own, so the
exception is caught by the default handler provided by the Java run-time system.

• Any exception that is not caught by your program will ultimately be processed by the
default handler.

15
Uncaught Exceptions(cont’d…)

• The default handler displays a string describing the exception, prints a

stack trace from the point at which the exception occurred, and

terminates the program.

• Here is the exception generated when the above example is executed:

java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)

16
Using try and catch

• Although the default exception handler provided by the Java run-time


system is useful for debugging, you will usually want to handle an
exception yourself.

• Doing so provides two benefits:


 First, it allows you to fix the error.

 Second, it prevents the program from automatically terminating.

• Most users would be confused if your program stopped running and


printed a stack trace whenever an error occurred! Fortunately, it is quite
easy to prevent this.
17
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.

18
Multiple catch Clauses
• In some cases, more than one exception could be raised by a single piece
of code.

• To handle such like 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.
19
Flowchart of Multi-catch Block

20
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
all of the nested try statements are exhausted.
• If no catch statement matches, then the Java run-time system will
handle the exception.

21
Chapter 5: packages

• It is a mechanism for partitioning the class name space into more


manageable chunks. A package is a container of classes and interfaces.

• A package represents a directory that contains related group of classes and


interfaces.

• For example, when we write statemens like:

• import java.io.*;

• Here we are importing classes of java.io package. Here, java is a directory


name and io is another sub directory within it. The ‘*’ represents all the
classes and interfaces of that io sub directory.
22
Package(cont’d…)

• We can create our own packages called user-defined

packages or extend the available packages.

• User-defined packages can also be imported into other

classes and used exactly in the same way as the Built-in

packages. Packages provide reusability.

23
Defining a Package
• To create a package 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.

• While the default package is fine for short, sample programs, it is inadequate

for real applications. Most of the time, you will define a package for your code.
24
Defining a Package…
• This is the general form to create package is:
 package pkg;

• Here, pkg is the name of the package. For example, the following
statement creates a package called MyPackage:
• package MyPackage;

• For example, the .class files for any classes you declare to be part of
MyPackage must be stored in a directory called MyPackage.

25
Defining a Package…
• The package statement simply specifies to which package the classes
defined in a file belong. It does not exclude other classes in other files
from being part of that same package.

• You can create a hierarchy of packages.

• To do so, simply separate each package name from the one above it
by use of a period.

• The general form of a multileveled package statement is shown here:


• package pkg1[.pkg2[.pkg3]];
26
Finding Packages

• Java run-time system where packages that you create are/is exist

• It can do this by the following three ways:

• First, by default, the Java run-time system uses the current working directory as
its starting point. Thus, if your package is in a subdirectory of the current
directory, it will be found.

• Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.

• Third, you can use the - classpath option with java and javac to specify the path
to your classes.
27
Access Modifier
Specifies the scope of the data members, class and methods.

• private members of the class are available with in the class only.
• The scope of private members of the class is “CLASS
SCOPE”.

• public members of the class are available anywhere .


• The scope of public members of the class is "GLOBAL
SCOPE".

28
Access Modifier…

• default members of the class are available with in the class,


outside the class and in its sub class of same package.
• It is not available outside the package. So the scope of default members
of the class is "PACKAGE SCOPE".

• protected members of the class are available with in the class,


outside the class and in its sub class of same package and also
available to subclasses in different package also.

29
Access Modifier…

30

You might also like