You are on page 1of 31

Exceptions

© Tata Consultancy Services ltd. May 14, 2020 1


Course Prerequisites
 Awareness of programming concepts.
 Completion of Core Java Overview.
 Completion of Core Java Data Types.
 Completion of Core Java - Inheritance Interfaces
 Completion of Core Java - Constructor Overloading
 Completion of Input-Output in Java
 Completion of JDBC

2
Course Objectives

 Overview of Java Exceptions


 Understand Java Exception Class Hierarchy
 Understand Exception catching and handling
 Illustration of all functionalities with code examples

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

 Java throws an exception in response to an unusual situation


 Exceptions can be thrown by the system or thrown by you
 Exceptions can be caught and dealt

6
How Exception Works?

 Exception handling begin search for handler that can deal with that particular error

Throws an object that encapsulates error information

7
Exception Class Hierarchy
Throwable

Error Exception

RuntimeException
IOException

8
Exception Class Hierarchy
 Exception is a class derived from Throwable

 Error describes the internal errors


- should not throw an object of such type

 Exception
- Runtime Exception
- IO Exception

 Runtime Exception
- a bad cast
- out-of-bound array access

9
Exception Class Hierarchy

 IO exception

- Trying to read past end of file


- Trying to open a malformed URL
- Trying to open non-existing file

 Runtime exception - your fault

 Malformed URL

- Different browsers can handle different kind of URLs


- The notion “malformed’’ depends on env.

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

Methods in Exception Class


- e.getMessage ( );
- e.printStackTrace();

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

public Image loadImage (String s )


throws EOFException, MalformedURLException
{
Code…
}
- Java enforces the user of this method to catch EOFException and
MalformedException

16
Catch Multiple Exceptions
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 }

17
Creating Own Exception Class

class MyException extends Exception {


public FileFormatException ( ) { }
public FileFormatException ( String s ) { //code }
}

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

NoRecordFound DataInputManda InvalidDataInput


Exption toryException Exception

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

You might also like