Exceptions in Java
Exceptions in Java
Exceptions in Java
2
Course Objectives
3
Session Outline
When a error occurs?
Java Exceptions
How Exception works?
Exception Class Hierarchy
Checked Vs. UnChecked Exceptions
Exception – Catching & Handling
Exceptions - throw
Exception - throws
Catch Multiple Exceptions
Creating Own Exception Class
Exception - An Example; Solution – 1; Solution - 2
Propagating the errors up the Stack
Catch where ever you want !!!
Your Own Application Exception Hierarchy
Some Common Practices
Exercise
Summary
References
4
When error occurs?
- Either because the programmer didn't anticipate every situation your code
would get into (or didn't have the time to test the program enough),
- Or because of situations out of the programmer's control (bad data from
users, corrupt files, network problems, hardware devices that don't respond etc.)
5
Java Exceptions
6
How Exception Works?
Exception handling begin search for handler that can deal with that particular error
7
Exception Class Hierarchy
Throwable
Error Exception
RuntimeException
IOException
8
Exception Class Hierarchy
Exception is a class derived from Throwable
Exception
- Runtime Exception
- IO Exception
Runtime Exception
- a bad cast
- out-of-bound array access
9
Exception Class Hierarchy
IO exception
Malformed URL
10
Checked Vs. UnChecked Exceptions
Checked exceptions :
represent invalid conditions in areas outside the immediate control of the program (invalid user input, database
problems, network outages, absent files)
are subclasses of Exception
methods are obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the
checked exception further up the stack, or handle it somehow)
Unchecked exceptions :
represent defects in the program (often invalid arguments passed to a non-private method)
are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException,
NullPointerException, or IllegalStateException
methods are not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they
almost always do not do so)
11
Exception – Catching & Handling
try
{
code
more code
more code
}
catch ( ExceptionType e )
{
handler code for this type
}
12
Exception – Catching & Handling
try
{ code that might throw exceptions }
catch ( MalformedURLException e1)
{ // action for malformed URLs }
catch ( UnknownHostException e2)
{ // action for unknown host }
catch ( IOException e3)
{ // action for all other I/O problems }
13
Exception – Catching & Handling
try {
code that throws exception
} catch (IOException e ) {
code to handle IOException
}
finally {
finally code(eg: closing file)
}
14
Exceptions - throw
try{
//if file not exists throw Exception
throw new Exception ( );
}catch(Exception e){
// code to handle exception
}
- Exception e = new Exception ( );
throw e ;
- throw new Exception(s);
15
Exception - throws
16
Catch Multiple Exceptions
try
{ code that might throw exceptions }
17
Creating Own Exception Class
try{
//if file not exists throw Exception
}catch(Exception e){
throw new MyException ( );
throw new MyException ( “Invalid File Format”);
}
18
Exception - An Example
A Practical Problem
readFile{
open the file;
determine its size;
allocate memory;
read the file into memory;
close the file;
}
19
Solution - 1
errorCodeType readFile{
initialisation errorCode=0;
open the file if (thefileIsOpen){
determine the length of the file; if(gotTheFileLength){
allocate memory; if(gotEnoughMemory){
read the file into memory;
if (readFailed){errorCode=-1;}}else {(errorCode=-2;)}}
else{errorCode=-3;}
Close the file;
20
Solution - 2
readFile{ try
{
open the file;
determine its size;
allocate memory;
read the file into memory;
close the file;
}
catch(fileOpenFailed){doSomething;}
catch(sizeDeterminationFailed){doSomething;}
catch(memoryAllocationFailed){doSomething;}
catch(readFailed){doSomething;}
catch(readFailed){doSomething;}
catch(fileCloseFailed){doSomething;}
21
Propagating the errors up the Stack
method1{
call Method2;
}
method2{
call Method3;
}
method3{
call readFile;
}
22
Catch where ever you want !!!
method1{
try{
call method2;
} catch(exception){
doErrorProcessing;}
}
method2 throws exception {
call method3;}
method3 throws exception {
call readFile;}
23
Your Own Application Exception Hierarchy
Exception
DataValidationException
24
Some Common Practices
Avoid empty catch blocks
Be specific in throws clause
Exception translation
Javadoc all “Checked” exceptions
Pass all pertinent data to exceptions
Avoid catching exceptions and rethrowing the same without doing anything
else like exception translation, exception data enrichment etc.
Do not use printStackTrace in production code
Use template for repeated try-catch
25
Exercise
Create an application checked exception hierarchy
Add sufficient logging information to the exceptions
Throw one of these exceptions from a nested method call
Create an exception handler and call from the appropriate place in the call
structure
Examine the stack trace of the exception
26
Course Summary
Java Exceptions
Usage of Exceptions – Catching and Handling
Exercise and Solutions
Common Practices
27
References
Skill port Courses (e-learning):
Java 2 (Platform 1.2)
Java 2: Language Basics
Java 2: Creating Classes
Java 2: Language Features
Java 2: Core Utilities
Java 2: Introduction to Creating GUIs
Java 2 Programming (Platform 1.3)
Client Development, Application Deployment, and Security (Platform
1.3)
Developing J2EE Clients
Packaging and Deploying J2EE Applications
Java 2 Security Features
Enterprise JavaBeans (Platform 1.3)
Developing EJBs
Persistence and Transactional Issues Affecting EJBs
28
References
Skill port Courses (e-learning):
J2EE Support Technologies (Platform 1.3)
Java Database Connectivity
RMI and the Java Message Service
CORBA and the Java IDL
Java 2 Programming (Platform 1.3)
Java 2 Language Basics
Creating Classes in Java 2
Java 2 Language Features
Core Java 2 Utilities
Introduction to Creating GUIs in Java 2
Overview of the J2EE Architecture (Platform 1.3)
J2EE Architecture
Servlets and JSPs (Platform 1.3)
Developing Servlets
Developing JSPs
Java Enterprise Development with the J2EE: J2EE Connector
The J2EE Connector Architecture
29
References
Skill port Courses (e-learning):
Java Programming with J2SE 1.4
Getting Started with Java
Operators and Flow Control in Java
Creating Classes in Java
Working with Classes in Java
Reference Types and Threading
Exception Handling and Assertions
Java Utilities
Java Applets
Basic GUI Development in Java
Java Enterprise Connectivity
Java Enterprise Connectivity: Swing and the JFC
Enterprise Connectivity: Java Database Connectivity (JDBC)
Java Enterprise Connectivity: Remote Method Invocation (RMI) and Serialization
Java Enterprise Connectivity: CORBA and the Java IDL
Java Enterprise Connectivity: Servlets
Java Enterprise Connectivity: Enterprise Java Beans (EJB)
Java Enterprise Connectivity: Security Features
30
References
Skill port Courses (e-learning):
Java Web Services
Web service technologies
Java technologies for web services
Java web service clients
31