0% found this document useful (0 votes)
0 views

Lecture 9 - Package and Exception Handling

The document provides an overview of Java packages and exception handling, detailing how to create and use packages, as well as the importance of managing exceptions in Java programs. It explains the structure of try, catch, and finally blocks, and distinguishes between checked and unchecked exceptions. Additionally, it covers how to create custom exception classes and the significance of maintaining program flow despite unexpected events.

Uploaded by

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

Lecture 9 - Package and Exception Handling

The document provides an overview of Java packages and exception handling, detailing how to create and use packages, as well as the importance of managing exceptions in Java programs. It explains the structure of try, catch, and finally blocks, and distinguishes between checked and unchecked exceptions. Additionally, it covers how to create custom exception classes and the significance of maintaining program flow despite unexpected events.

Uploaded by

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

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Package and Exception Handling

(IT069IU)

Nguyen Trung Ky

📧 [email protected]

🌐 it.hcmiu.edu.vn/user/ntky
1
Previously,
- Java Generic Collections
- Type-Wrapper Classes for Primitive Types
- Autoboxing vs Auto-unboxing
- List
- ArrayList
- Vector
- LinkedList

2
Agenda Today
• Packages
• Exception Handling
• try block

• catch block

• finally block

• custom exception class

3/11
Packages
• A package is a grouping of related classes, interfaces types providing access
protection and name space (set of pre-defined names) management.
• Syntax to create a new package:
package [package name];
• This statement must be the first line in the source file.
• There can be only one package statement in each source file, and it applies to all
types in the file.
• The compiler will read source code line-by-line from the beginning of the source
file. So, the first work must be carried out is creating the folder and the folder
name is the package name. The package information will be added to classes in
this package.

4/11
Using Packages Members
• To use a public package member from outside its package, we can:
• Refer to the member by its fully qualified name
graphics.Rectangle myRect = new graphics.Rectangle();
• Import the package member
import graphics.Rectangle;

Rectangle myRectangle = new Rectangle();
• Import the member's entire package
import graphics.*;

Rectangle myRectangle = new Rectangle();
• 2 packages can contain 2 classes which have the same name
pkg1.ClassA obj1;
pkg2.ClassA obj2;
5/11
Exceptions
• Exception: Error beyond the control of a program. When an exception occurs,
the program will terminate abruptly.
• When a program is executing something occurs that is not quite normal from the
point of view of the goal at hand.
• For example:
• a user might type an invalid filename;
• An accessed file does not exist or might contain corrupted data;
• a network link could fail;
• …

• Circumstances of this type are called exception conditions in Java and are
represented using objects (All exceptions descend from the
java.lang.Throwable).

6/11
Exceptions
• The following program causes an exception.

Exceptions are pre-defined data


(Exception classes) thrown by JVM
and they can be caught by code in the
program

7/11
Why we need Exception Handling

• Java exception handling is important because it helps


maintain the normal, desired flow of the program even
when unexpected events occur.
• If Java exceptions are not handled, programs may crash or
requests may fail. This can be very frustrating for customers
and if it happens repeatedly, you could lose those
customers.

8/11
How to handle exceptions in Java:
try catch finally
try {
< statements may cause exceptions >
try block }
false
e? catch ( ExceptionType1 e1 ) {
true < statements handle the situation 1>
}
catch block catch ( ExceptionType2 e2) {
< statements handle the situation 2>
}
finally block
finally {
< statements are always executed >
If no exception is thrown }
in the try block, all catch blocks
are bypassed

If an exception arises, the first matching catch block, if any, is executed, and the
others are skipped
9/11
Types of Exceptions
Checked Exceptions
(We must use the try
catch blocks)
Unchecked- Exceptions
Program Bugs
(We may not use the
Refer to the Java.lang documentation for try catch blocks)
more information.

10/11
Two Types of Exception
• Checked exception:
• Checked exceptions represent errors outside the control of the
program.
• For example, caused by faults outside code like missing files,
invalid class names, and networking errors.

• Must be handled by either the try-catch mechanism or the throws-


declaration mechanism during compile time.

11/11
Two Types of Exception
• Unchecked exception:
• In contrast to a checked exception, an unchecked
exception represents an error in programming logic, not
an erroneous situation that might reasonably occur during
the proper use of an API.
• For example, if we divide a number by 0, Java will
throw ArithmeticException.

12/11
Compare checked and unchecked exceptions

13/11
Hierarchy of Exception Classes

14/11
Catching specific/general-level exception

15/11
Throwing exceptions in methods
May we intentionally throw an exception? → YES

16/11
Exception Propagations
catch(...)
A()

B()
Stack for A()

Stack for B() C()

Stack for C()


D() Exception
Stack for D()
When an exception occurs at a method, program
Stack trace stack is containing running methods ( method A
calls method B,….). So, we can trace statements
related to this exception.
17/11
Exception
Propagations

18/11
Catching Exceptions…
Using try…catch to input an integer 10<=n<=50
Scanner in = new Scanner(System.in);
boolean cont = true;
int n;
do {
try {
System.out.print(“Enter a number: ");
a = Integer.parseInt(in.nextLine());
cont = false;
} catch (Exception e) {
System.out.println("Required integer!");
}
} while (cont == true|| n<10 || n>50);
19/11
The finally block
• A try block may optionally have a finally block associated with it.
• The code within a finally block is guaranteed to execute no matter
what happens in the try/catch code that precedes it.
• The try block executes to completion without throwing any
exceptions whatsoever.
• The try block throws an exception that is handled by one of the
catch blocks.
• The try block throws an exception that is not handled by any of
the catch blocks

20/11
Nesting of try/catch blocks
• A try statement may be nested inside either the try or catch block of
another try statement.
try {
// Pseudo code.
open a user-specified file
}
catch (FileNotFoundException e) {
try {
// Pseudo code.
open a DEFAULT file instead ...
}
catch (FileNotFoundException e2) {
// Pseudo code.
attempt to recover ...
}
}
21/11
Creating Your Own Exception Classes

• Decide whether you want a checked or a runtime exception.


• Checked exceptions should extend java.lang.Exception or

one of its subclasses.


• Runtime exceptions should extend

java.lang.RuntimeException or one of its subclasses

22/11
Creating Your Own Exception Classes

Create your own exception class with it’s constructor


class InvalidAge extends Exception{
public InvalidAge(String mes) {
super(mes);
}
}

23/11
Creating Your Own Exception Classes

//Use it in some method


class MyClass{
public void MyMethod(int a) throws InvalidAge{
if(a<0)
throw new InvalidAge("Age invalid!");
}
}

24/11
Creating Your Own Exception Classes

//Using try-catch when this method is called


try {
MyClass class1 = new MyClass();
class1.MyMethod(-5);
} catch (InvalidAge ex) {
System.out.println(ex.getMessage());
}

25/11
Thank you for your listening!

“Motivation is what gets you started.


Habit is what keeps you going!”
Jim Ryun

27

You might also like