0% found this document useful (0 votes)
28 views43 pages

MZ Chapter - 4 and 5 - Exception Handling and Packages Oop

Uploaded by

kidus seyoum
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)
28 views43 pages

MZ Chapter - 4 and 5 - Exception Handling and Packages Oop

Uploaded by

kidus seyoum
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/ 43

Chapter Four

Exception Handling
Exception Handling
• 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.

• Hence, in this lecture we will learn about Java exceptions,


Exception Types, and the difference between checked
and unchecked exceptions.
What is Exception?
• An exception is a problem or an abnormal Condition 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 needs
to be handled.
• It is an object thrown at runtime.
Exception … Cont
• An exception can occur for many different reasons. Following
are some scenarios where an exception occurs.
– Attempting to divide by zero (arithmetic exception)
– Reading a decimal value when an integer is expected
(number format exception)
– Attempting to write to a file that does not exist (I/O
exception)
– Referring to a non existent character in a string or non
existent array index (Array index out of bounds exception)
– A network connection has been lost in the middle of
communication, or JVM has run of memory, hard disk failure
• Some of these exceptions are caused by user error, other by
programming error, and others by physical resources that
The causes of exception
 User error (Invalid input): Exceptions can be triggered when
the program receives invalid or unexpected input from the user.
E.g., attempting to convert a non-numeric string to a number or
dividing by zero can result in exceptions.

 Resource unavailability: Exceptions can occur when a required


resource is not available or cannot be accessed. This could include
file I/O errors, network connectivity issues, or database connection
problems.

 Programming errors: Mistakes in the code, such as logical


Introduction cont.
• No matter how well-designed a program is, there is always the
chance that some kind of error arises during its execution.

• Raising an exception halts normal execution abruptly and


alternative statements are sought to be executed.

• A well-designed program should include code to guard against


errors and other exceptional conditions when they arise.

• In Java, the preferred way of handling such conditions is to use


Exception Handling – an approach that separates a program’s
normal code from its error-handling code.
Introduction cont.
• Valid Java programming language code must honour the Catch
or Specify Requirement.

• This means that code that might throw certain exceptions must
be enclosed by either of the following:
– A try statement that catches the exception.
try... catch
– A method that specifies that it can throw the exception.
throws or throw

• Code that fails to honour the Catch or Specify Requirement will


not compile.
Java Exception Hierarchy
• Java class library contains number of predefined exceptions

• All exception classes are subtypes of the java.lang.Exception


class.

• The Exception class is a subclass of the Throwable class.


Throwable class has another subclass called Error.

• Errors are not normally trapped/handled from the Java programs.


These conditions normally happen in case of server/serious
failure, which are not handled by the java programs.

• Errors are generated to indicate errors generated by runtime


Hierarchy of Java Exception classes
Types of Exception
• Some of exceptions are
caused by
– User error,

– Programmer error,

– Physical resources that have


failed in some manner.

• Based on these, we have three


categories of exception
Checked Exception
• The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.

• Any code that may throw a checked exception must either


catch the exception using a try-catch block or specify that it
throws the exception in the method signature using the
"throws" keyword.
• For example,
– IOException, SQLException, ClassNotFoundException etc.

• Checked exceptions are checked at compile-time.


Checked Exception Conn…
• A checked exception is an exception that is checked (notified)
by the compiler at compilation time, these are also called as
compile time exceptions.

• These exceptions cannot simply be ignored, 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 a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
import java.io.*;
import java.io.FileNotFoundException; Example
public class FileNotFoundExceptionDemo {
public static void main(String args[])
throws FileNotFoundException {
File file = new
File("E://file.txt");
FileReader fr = new
FileReader(file);
}
}
Unchecked Exception
• The classes that inherit the RuntimeException are known as

unchecked exceptions and the compiler does not enforce


the Catch or Specify Requirement for them.
• For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.

• Unchecked exceptions are not checked at compile-time, but


they are checked at runtime.
Categories of Exception - Errors
 Errors represent exceptional conditions that are generally
beyond the control of the application, such as
OutOfMemoryError or StackOverflowError, network connection
problem, thread death.

 Like unchecked exceptions, errors do not need to be declared


in a method's throws clause, and the Catch or Specify
Requirement does not apply to them.
Java Exception Keywords
Keyword Description

try The "try" keyword is used to specify a block where we


should place an exception code. It means we can't use
try block alone. The try block must be followed by either
catch or finally.

catch The "catch" block is used to handle the exception. It must


be preceded by try block which means we can't use catch
block alone. It can be followed by finally block later.
Java Exception Keywords cont.
Keyword Description

finally The "finally" block is used to execute the necessary code of


the program. It is executed whether an exception is
handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It


specifies that there may occur an exception in the method.
It doesn't throw an exception. It is always used with
method signature.
Sample Program [1]
What’s the output of the following program?

public class SampleProgram {


public static void main(String args[]) {
String[] greek = {"Alpha", "Beta",
"Gamma"};
System.out.println(greek[3]);
}
}

19
Sample Program [1] cont.
• Compiles successfully but encounters a problem when it
runs

• The Java interpreter made note of the exception by


displaying the error message and stopped the program.

• An object of type ArrayIndexOutOfBoundException is


created to alert the user – you have used an array element
that isn’t within the array’s boundaries.

• ArrayIndexOutOfBoundException is a subclass of
What happens when exception
occurs?
• When an exception occurs within a method, the method creates an
object and hands it off to the runtime system.

• The object created is called an exception object, contains information


about the error, including its type and the state of the program when the
error occurred.

• Creating an exception object and handing it to the runtime system


is called throwing an exception.

• After a method throws an exception, the runtime system attempts to find


something to handle it. The set of possible "somethings" to handle the
exception is the ordered list of methods that had been called to get to the
Call Stack

 The runtime system searches the call stack for a method that
contains a block of code that can handle the exception. This block of
code is called an exception handler.
 The search begins with the method in which the error occurred and
proceeds through the call stack in the reverse order in which the methods
were called.
 If the runtime system exhaustively searches all the methods on the call
SumNumbers [1]
public class SumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i < arguments.length; i++)
sum += Float.parseFloat(arguments[i]);
System.out.println("Those numbers add up to "+
sum);
}
}

23
SumNumbers [2]
public class SumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i < arguments.length; i++)
sum += Float.parseFloat(arguments[i]);
System.out.println("Those numbers add up to "+
sum);
}
}

24
Example [1]
import java.util.Scanner;

public class InputMismatch {


public static void main(String[] arguments) {
Scanner sc = new Scanner(System.in);
int x;
x = sc.nextInt();
}
}

If we give either 5.6 or some string “asas” or character


to the above code while entering from keyboard, we get
java.util.InputMismatchException 25
Handling an Exception
• Exception handling is accomplished through
 “try…catch” mechanism OR
 by “throws or throw” clause in method declaration

• For any code that throws a checked exception, we should


either handle ourselves or pass the exception “up the
chain” (to a parent class)

• To handle, we write “try…catch” block

• To pass, we declare a throws clause in our method or


• Using a try-catch block: This allows you to handle the exception within
try
the same method or {
block of code.
// Code that may throw a checked exception
} catch (SomeCheckedException e) {
// Handle the exception here
}

• Specifying the exception in the method signature: You can declare that a
method throws a checked exception by including the exception type in the
method signature using the "throws" keyword. This means that any code
calling the method must either handle the exception or declare it to be
thrown as well. public void someMethod() throws
SomeCheckedException {
// Code that may throw a checked
exception
Catching Exceptions in a try-catch
Block
try {
// Code that may throw an exception
} catch (ExceptionType1 ex1) {
// Exception handling for ExceptionType1
} catch (ExceptionType2 ex2) {
// Exception handling for ExceptionType2
} finally {
// Code that is always executed,
// regardless of whether an exception occurred or
not
NewSumNumbers [1]
public class NewSumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i<arguments.length; i++){
try {
sum += Float.parseFloat(arguments[i]);
}
catch (NumberFormatException e) {
System.out.println(arguments[i] + " isn’t a
number.");
}
}
System.out.println("Those numbers add up to "+ sum);
}
}
NewSumNumbers [Output]
Catching Several Different Exceptions
public class DivideNumbers {
public static void main(String[] arguments) {
if (arguments.length == 2) {
int result = 0;
try {
result =
Integer.parseInt(arguments[0])/Integer.parseInt(arguments[1]);
System.out.println("Result = " + result);
}
catch (NumberFormatException e) {
System.out.println("Both arguments must be numbers.");
}
catch (ArithmeticException e) {
System.out.println("You cannot divide by zero");
}
}
}
}
finally : Example
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" +
a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println(“Finally statement is
executed");
}
}
}
Exceptions Methods
• Following is the list of important methods available in
the Throwable class.

r.No. Method & Description


1 public String getMessage()
Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.

2 public Throwable getCause()


Returns the cause of the exception as represented by a Throwable object.

3 public String toString()


Returns the name of the class concatenated with the result of getMessage().
r.No Method & Description
.

4 public void printStackTrace()


Prints the result of toString() along with the stack trace to System.err,
the error output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The
element at index 0 represents the top of the call stack, and the last
element in the array represents the method at the bottom of the call
stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack
Chapter Five
Packages
What is package?
• Packages are used in Java, in-order to avoid name conflicts

and to control access of class, interface and enumeration etc.

• A package can be defined as a group of similar types of

classes, interface, enumeration or sub-package.

• Using package it becomes easier to locate the related classes

and it also provides a good structure for projects with

hundreds of classes and other files.


Advantages of using package
– Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
– It provides access protection.
– It removes naming collision.
– Provides code reusability capability
– We can create our own package or extend already
available package.
Types of Java Package
• Two types of java package
includes
– Built-in package lang
– User Defined Package
net io
• Built-in packages Built-in
– All existing java libraries are packag
built-in packages
swin es
util
g
awt
User Defined packages
• Programmers can define their own packages to
bundle/ categorize group of related
classes/interfaces

• It is created using package command followed by


name of the package as the first statement in java
source file.
• Syntax
package packageName;
Compile package statement
• Compiling a java program that contain package
statement follows uses –d option and the syntax is
given as
javac –d Destination-Folder FileName.java
Example

package animals;
package animals;
public class MammalInt implements Animal {
public void eat() {
interface Animal {
System.out.println("Mammal eats");
public void eat();
}
public void travel();
public void travel() {
}
System.out.println("Mammal
travels");
Compilation Process }
public int noOfLegs() {
return 0;
javac -d . Animal.java
}
javac -d . MammalInt.java public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
The import Keyword
• Classes in the same package find each other without any
special syntax.

• But, if classes are in different packages one class should


include another classes’ package to access its member.
• This is possible through import

• Syntax
import packageName.*; (using .* wild card)
import packageName.className;
Example
package payroll;
public class Boss {
public void payEmployee(Employee e) {
e.mailCheck();
}
}

• if the Employee class is not in the payroll package? The Boss class must
then use one of the following techniques for referring to a class in a
different package.
import payroll.*;
import payroll.Employee;
Package Summary points
– A package is always defined as a separate folder having
the same name as the package name.
– Store all the classes in that package folder.

– All classes of the package which we wish to access


outside the package must be declared public.
– All classes within the package must have the package
statement as its first line.
– All classes of the package must be compiled before use

You might also like