SlideShare a Scribd company logo
Exception Handling Fundamentals
‐
An exception is a problem that arises during the
execution of a program. When an Exception(un
wanted event) occurs the normal flow of the
program is disrupted and the program/Application
terminates abnormally.
Some of the reasons for an exception
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of
communications or the JVM has run out of memory.
If the exception Object is not Handled properly, the
interpreter will display the error and will terminate
the program.
It is highly recommended to handle exceptions
The main objective of exception handling is graceful
termination of program.
Exception handling doesn’t mean repairing an
exception we have to provide alternative way to
continue rest of the program normally is the
concept of exception handling .
exception handling can be managed by five
keywords:
1.try,
2. catch,
3.throw,
4.throws,
5.finally.
This is the general form of an exception-handling block
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2
}
//……
finally
{ // block of code to be executed after try block ends
}
Uncaught Exceptions
Class Test
{
public static void main(String args[])
{
doStuff();
}
public static doStuff()
{
doMoreStuff();
}
public static doMoreStuff()
{ Java Runtime Stack
System.out.println(10/0);
}
}
doMoreStuff()
doStuff()
Main()
Steps to handle Uncaught Exceptions
1.Inside a method if any exception occurs the method in
which its raised is responsible to create exception object
by including the following information
1.name of exception
2.description of exception
3.location at which exception occurs(stack trace)
2.After creation of exception object method handovers
that object to the jvm.
3.Jvm will check whether the method contains any
exception handling code or not if the method doesn’t
contain exception handling code then jvm terminates
that method abnormally and removes corresponding
entry from the stack.
4. jvm identifies callers method and checks whether caller
method contains any handling code or not. If the caller
method doest contain handling code then jvm terminates
that caller method also abnormally and removes
corresponding entry from the stack this process will be
continued until the main method. if the main method also
doesn’t contain handling code then jvm terminates main
method also abnormally and removes corresponding entry
from the stack.
5.Then JVM handovers responsibility of exception handling to
default exception handler, which is the part of jvm.
6.Defaulty Exception Handler prints exception information in
the following format and terminates program abnormally.
Exception in thread in XXX : name of the exception:
Description: stack trace
Hierarchy of Exception classes
Exception
Most of the times exceptions are caused by our program and these are
recoverable.
Child classes for Exception
1.IOException
i.EOF Exception
ii.FileNotFoundException
iii.InteruptedIOException
2.SQLException
3.ServletExcetion
4.Runtime Exception
i. ArithmeticException
ii. NumberFormatException
iii. ArrayIndexOutOfBoundsException
iv.NullPointerException
5.RemoteException
6.Interuptedexception
Error
Most of the times errors are not caused by our
program and these are due to lack of system
resources. Errors are non recoverable.
Child classes for Error
1.VMError
i.StackOverFlowError
ii.OutOfMemoryError
2.AssertionError
Types of Exception
There are mainly two types of exceptions
1.Checked Exception
2.Unchecked Exception
Checked Exception:
The exceptions which are checked by compiler for smooth
execution of the program are called checked exception.
Example: FileNotFoundException, SQLException
In our program if there is chance of rising checked
exception then compulsory we should handle that
cheeked exception either by try, catch or throws key
word otherwise we will get compile time error.
Unchecked Exception
The exception which are not checked by compiler whether
programmer handling or not such type of exceptions are
called Unchecked Exception.
Example
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Note :
1.Whether it is checked or unchecked exception that
occurs at runtime only there is no chance of occurring
any exception at compile time.
2.RuntimeException and its child classes, Error and its child
classes are unchecked except these reaming are
checked.
Exception Handling Using Try Catch
It is highly recommended to handle exceptions.
The code which may raise exception is called risky code and we have to
define that code inside the try block.
And the corresponding handling code we have to define inside the catch
block.
Syntax
Try
{
Risky code
}
Catch(Exception e)
{
Handling code;
}
Example with out Try catch
Class test
{
Public static void main(String args[])
{
System.out.println(“statement1”);
System.out.println(10/0);
System.out.println(“statement3”);
}
}
Out Put:
Statement1
Exception:AE:divide by zero
Example with Try catch
Class test
{
Public static void main(String args[])
{
System.out.println(“Before Exception ”);
try
{
System.out.println(10/0);
}
Catch(ArithmeticException e)
{
System.out.println(10/2);
}
System.out.println(“After catch statement.”);
}
}
Out Put:
Statement1
5
Statement3
Control Flow in Try Catch
Try
{
Statement1
statement2
statement3
}
Catch(Exception e)
{
statement4
}
Statement5
Case1: No Exception
Out :1,2,3,5 -normal termination
Case2: if an exception raised at statement 2 and corresponding catch block
matched
Out put:1,4,5-normal termination
Case 3: if an exception raised at statement 2 and corresponding catch block
not matched
Out Put :1,-- abnormal termination
Case 4: if an exception raised at statement 4 or statement 5
Out put: Abnormal termination
Note :
1. With in the try block if any where exception raised then rest of the try block
won’t be executed even though we handled exception. Hence we have to
write only risky code into the try block.
2. In addition to try block there may be a chance of raising an exception inside
catch and finally blocks.
3. If any statement which is not part of try block and raise an exception then it
is always abnormal termination.
Methods to print Exception Information
Throwable class defines the following methods to
print Exception Information
Note : internally default exception handler will use printStackTrace to print exception
information to the console
Method Printable Format
printStackTrace() Name of the Exception : Description :
Stack Trace
toString() Name of the Exception : Description
getMessage() Description
Example
class Test
{
public static void main(String args[])
{
try
{
system.out.println(10/0);
}
catch(ArithmeticException e)
{
e.printStackTrace();
System.out.println(e.toString());
System.out.println(e.getMessage());
}
}
}
Java.lang:AE:/ by
Zero
At test.Main()
Java.lang:AE: / by
Zero
/ by Zero
Try with multiple catch blocks
The way of handling an exception is varied from exception to
exception hence for every exception type, it is highly
recommended to take separate catch block that is try with
multiple catch blocks is always possible and recommended to
use.
Example
Try
{
Risky code;
}
Catch(Exception e)
{
}
Bad programming practice
Example:
Try
{
Risky code;
}
Catch(Arithmetic Exception e)
{
Perform any Arithmetic operation;
}
Catch(FileNotFoundException e)
{
Use local file instead of remote file;
}
Catch(Exception e)
{
//Default Exception Handling;
}
Best Programming Practice
If try with multiple catch blocks present then the order of catch blocks is
very important.
We have to take child first and then parent otherwise we will get compile
time error saying
Exception XXX has already been caught
Example
Try
{
Risky code
}
Catch(Exception e)
{
}
Catch(ArithmeticException e)
{
}
Out put : Compile time error
Try
{
Risky code
}
Catch(ArithmeticException e)
{
}
Catch(Exception e)
{
}
Output:
Exception handled .
Nested try Statements
One try-catch block can be present in the another
try’s body. This is called Nesting of try catch blocks.
Each time a try block does not have a catch handler
for a particular exception, the stack is unwound and
the next try block’s catch handlers are inspected for
a match.
If no catch block matches, then the java run-time
system will handle the exception.
Syntax of Nested try Catch
.... //Main try block
try
{
statement 1;
statement 2;
//try-catch block inside another try block
try
{
statement 3;
statement 4;
}
catch(Exception e1)
{
//Exception Message
}
}
catch(Exception e3) //Catch of Main(parent) try block
{
//Exception Message
}
Throw Keyword
Some times we can create exception object explicitly and handover to jvm
manually, for this we have to use throw key word.
Throw new ArithmeticException(“/ by zero”);
The main objective of throw key word is to handover our created
exception object to jvm manually.
Example
Class test
{
Public static void main(String args[])
{
Throw new ArithmeticException(“/ by zero”);
}
}
Best use of throw keyword is for user defined exceptions or customized
exceptions.
Throws keyword
In our program if there is a possibility of raising checked exception then compulsory we
should handle that checked exception otherwise we will get compile time error saying
Unreported Exception XXX must be caught or declared to be thrown
Syntax
type method-name(parameter-list) throws exception-list
{ // body of method }
Example
Class test
{
Public static void main(String args[])
PrintWriter pw=new PrintWriter(“abc.txt”);
pw.println(“hello”);
}
}
Compile time error: Unreported Exception java.io.FileNotFound; must be caught or
declared to be thrown
We can handle this compile time error by using Throws keyword or by
using Try catch.
The purpose of throws keyword is to delegate the responsibility of
exception handling to the caller (it may be another method or JVM)
then caller method is responsible to handle that exception
Example
Class test
{
Public static void main(String args[]) throws FileNotFoundException
{
PrintWriter pw=new PrintWriter(“abc.txt”);
pw.println(“hello”);
}
}
Throws key word requires only for checked
exception.
Throws key word required only to convince
compiler and usage of throws keyword
doesn't prevent abnormal termination of the
program.
Finally block
finally block is a block that is used to execute important(clean up) code such as closing
connection, stream etc.
finally block is always executed whether exception is handled or not.
finally block follows try or catch block.
Example
Try
{
Risky code
}
Catch(Exception e)
{
}
finally
{
Clean up code;
}
Java’s Built-in Exceptions
Unchecked Exceptions
Checked Exceptions
User defined Exception subclass
We can also create our own exception sub class simply by extending java Exception class.
Example
class TooYoungException extends RuntimeException
{
TooYoungException(String s)
{
super(s);
}
}
class CustException
{
public static void main(String args[])
{
int age=Integer.parseInt(args[0]);
if(age<18)
{
throw new TooYoungException("you are too young so u r not allowed");
}
else
{
System.out.println("u r allowed");
}
}
}
Chained Exception
Chained Exception was added to Java in JDK 1.4. This feature allow
you to relate one exception with another exception, i.e one
exception describes cause of another exception.
Two new constructors and two new methods were added to
Throwable class to support chained exception.
Throwable( Throwable cause )
Throwable( String str, Throwable cause )
getCause() and initCause() are the two methods added to
Throwable class.
getCause() method returns the actual cause associated with current
exception.
initCause() set an underlying cause(exception) with invoking
exception.
Example
import java.io.IOException;
public class ChainedException
{
public static void divide(int a, int b)
{
if(b==0)
{
ArithmeticException ae = new ArithmeticException("top layer"); ae.initCause( new IOException("cause") );
throw ae;
}
else
{
System.out.println(a/b);
}
}
public static void main(String[] args)
{
Try
{
divide(5, 0);
}
catch(ArithmeticException ae)
{
System.out.println( "caught : " +ae);
System.out.println("actual cause: "+ae.getCause());
}
}
}
Ad

Recommended

Exceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Interface andexceptions
Interface andexceptions
saman Iftikhar
 
Java exception handling
Java exception handling
BHUVIJAYAVELU
 
Java Exception handling
Java Exception handling
Garuda Trainings
 
java exception.pptx
java exception.pptx
SukhpreetSingh519414
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception Handling.pptx
Exception Handling.pptx
primevideos176
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exceptionhandling
Exceptionhandling
Nuha Noor
 
Exceptions in java
Exceptions in java
JasmeetSingh326
 
Exception handling in java
Exception handling in java
Elizabeth alexander
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
PACKAGES, INTERFACES AND EXCEPTION HANDLING
PACKAGES, INTERFACES AND EXCEPTION HANDLING
mohanrajm63
 
Java Day-5
Java Day-5
People Strategists
 
L14 exception handling
L14 exception handling
teach4uin
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Z blue exception
Z blue exception
Narayana Swamy
 
Exception handling in java
Exception handling in java
gopalrajput11
 
Chap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt .
happycocoman
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
EventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
working with interfaces in java programming
working with interfaces in java programming
Parameshwar Maddela
 

More Related Content

Similar to Exception‐Handling in object oriented programming (20)

Exception Handling.pptx
Exception Handling.pptx
primevideos176
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exceptionhandling
Exceptionhandling
Nuha Noor
 
Exceptions in java
Exceptions in java
JasmeetSingh326
 
Exception handling in java
Exception handling in java
Elizabeth alexander
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
PACKAGES, INTERFACES AND EXCEPTION HANDLING
PACKAGES, INTERFACES AND EXCEPTION HANDLING
mohanrajm63
 
Java Day-5
Java Day-5
People Strategists
 
L14 exception handling
L14 exception handling
teach4uin
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Z blue exception
Z blue exception
Narayana Swamy
 
Exception handling in java
Exception handling in java
gopalrajput11
 
Chap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt .
happycocoman
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Exception Handling.pptx
Exception Handling.pptx
primevideos176
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exceptionhandling
Exceptionhandling
Nuha Noor
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
PACKAGES, INTERFACES AND EXCEPTION HANDLING
PACKAGES, INTERFACES AND EXCEPTION HANDLING
mohanrajm63
 
L14 exception handling
L14 exception handling
teach4uin
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Exception handling in java
Exception handling in java
gopalrajput11
 
Chap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt .
happycocoman
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 

More from Parameshwar Maddela (11)

EventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
working with interfaces in java programming
working with interfaces in java programming
Parameshwar Maddela
 
introduction to object orinted programming through java
introduction to object orinted programming through java
Parameshwar Maddela
 
multhi threading concept in oops through java
multhi threading concept in oops through java
Parameshwar Maddela
 
Object oriented programming -QuestionBank
Object oriented programming -QuestionBank
Parameshwar Maddela
 
file handling in object oriented programming through java
file handling in object oriented programming through java
Parameshwar Maddela
 
22H51A6755.pptx
22H51A6755.pptx
Parameshwar Maddela
 
swings.pptx
swings.pptx
Parameshwar Maddela
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
02_Data Types in java.pdf
02_Data Types in java.pdf
Parameshwar Maddela
 
Intro tooop
Intro tooop
Parameshwar Maddela
 
EventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
working with interfaces in java programming
working with interfaces in java programming
Parameshwar Maddela
 
introduction to object orinted programming through java
introduction to object orinted programming through java
Parameshwar Maddela
 
multhi threading concept in oops through java
multhi threading concept in oops through java
Parameshwar Maddela
 
Object oriented programming -QuestionBank
Object oriented programming -QuestionBank
Parameshwar Maddela
 
file handling in object oriented programming through java
file handling in object oriented programming through java
Parameshwar Maddela
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
Ad

Recently uploaded (20)

Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
penafloridaarlyn
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
penafloridaarlyn
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Ad

Exception‐Handling in object oriented programming

  • 1. Exception Handling Fundamentals ‐ An exception is a problem that arises during the execution of a program. When an Exception(un wanted event) occurs the normal flow of the program is disrupted and the program/Application terminates abnormally. Some of the reasons for an exception • A user has entered an invalid data. • A file that needs to be opened cannot be found. • A network connection has been lost in the middle of communications or the JVM has run out of memory.
  • 2. If the exception Object is not Handled properly, the interpreter will display the error and will terminate the program. It is highly recommended to handle exceptions The main objective of exception handling is graceful termination of program. Exception handling doesn’t mean repairing an exception we have to provide alternative way to continue rest of the program normally is the concept of exception handling .
  • 3. exception handling can be managed by five keywords: 1.try, 2. catch, 3.throw, 4.throws, 5.finally.
  • 4. This is the general form of an exception-handling block try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } //…… finally { // block of code to be executed after try block ends }
  • 5. Uncaught Exceptions Class Test { public static void main(String args[]) { doStuff(); } public static doStuff() { doMoreStuff(); } public static doMoreStuff() { Java Runtime Stack System.out.println(10/0); } } doMoreStuff() doStuff() Main()
  • 6. Steps to handle Uncaught Exceptions 1.Inside a method if any exception occurs the method in which its raised is responsible to create exception object by including the following information 1.name of exception 2.description of exception 3.location at which exception occurs(stack trace) 2.After creation of exception object method handovers that object to the jvm. 3.Jvm will check whether the method contains any exception handling code or not if the method doesn’t contain exception handling code then jvm terminates that method abnormally and removes corresponding entry from the stack.
  • 7. 4. jvm identifies callers method and checks whether caller method contains any handling code or not. If the caller method doest contain handling code then jvm terminates that caller method also abnormally and removes corresponding entry from the stack this process will be continued until the main method. if the main method also doesn’t contain handling code then jvm terminates main method also abnormally and removes corresponding entry from the stack. 5.Then JVM handovers responsibility of exception handling to default exception handler, which is the part of jvm. 6.Defaulty Exception Handler prints exception information in the following format and terminates program abnormally. Exception in thread in XXX : name of the exception: Description: stack trace
  • 9. Exception Most of the times exceptions are caused by our program and these are recoverable. Child classes for Exception 1.IOException i.EOF Exception ii.FileNotFoundException iii.InteruptedIOException 2.SQLException 3.ServletExcetion 4.Runtime Exception i. ArithmeticException ii. NumberFormatException iii. ArrayIndexOutOfBoundsException iv.NullPointerException 5.RemoteException 6.Interuptedexception
  • 10. Error Most of the times errors are not caused by our program and these are due to lack of system resources. Errors are non recoverable. Child classes for Error 1.VMError i.StackOverFlowError ii.OutOfMemoryError 2.AssertionError
  • 11. Types of Exception There are mainly two types of exceptions 1.Checked Exception 2.Unchecked Exception Checked Exception: The exceptions which are checked by compiler for smooth execution of the program are called checked exception. Example: FileNotFoundException, SQLException In our program if there is chance of rising checked exception then compulsory we should handle that cheeked exception either by try, catch or throws key word otherwise we will get compile time error.
  • 12. Unchecked Exception The exception which are not checked by compiler whether programmer handling or not such type of exceptions are called Unchecked Exception. Example ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Note : 1.Whether it is checked or unchecked exception that occurs at runtime only there is no chance of occurring any exception at compile time. 2.RuntimeException and its child classes, Error and its child classes are unchecked except these reaming are checked.
  • 13. Exception Handling Using Try Catch It is highly recommended to handle exceptions. The code which may raise exception is called risky code and we have to define that code inside the try block. And the corresponding handling code we have to define inside the catch block. Syntax Try { Risky code } Catch(Exception e) { Handling code; }
  • 14. Example with out Try catch Class test { Public static void main(String args[]) { System.out.println(“statement1”); System.out.println(10/0); System.out.println(“statement3”); } } Out Put: Statement1 Exception:AE:divide by zero
  • 15. Example with Try catch Class test { Public static void main(String args[]) { System.out.println(“Before Exception ”); try { System.out.println(10/0); } Catch(ArithmeticException e) { System.out.println(10/2); } System.out.println(“After catch statement.”); } } Out Put: Statement1 5 Statement3
  • 16. Control Flow in Try Catch Try { Statement1 statement2 statement3 } Catch(Exception e) { statement4 } Statement5
  • 17. Case1: No Exception Out :1,2,3,5 -normal termination Case2: if an exception raised at statement 2 and corresponding catch block matched Out put:1,4,5-normal termination Case 3: if an exception raised at statement 2 and corresponding catch block not matched Out Put :1,-- abnormal termination Case 4: if an exception raised at statement 4 or statement 5 Out put: Abnormal termination Note : 1. With in the try block if any where exception raised then rest of the try block won’t be executed even though we handled exception. Hence we have to write only risky code into the try block. 2. In addition to try block there may be a chance of raising an exception inside catch and finally blocks. 3. If any statement which is not part of try block and raise an exception then it is always abnormal termination.
  • 18. Methods to print Exception Information Throwable class defines the following methods to print Exception Information Note : internally default exception handler will use printStackTrace to print exception information to the console Method Printable Format printStackTrace() Name of the Exception : Description : Stack Trace toString() Name of the Exception : Description getMessage() Description
  • 19. Example class Test { public static void main(String args[]) { try { system.out.println(10/0); } catch(ArithmeticException e) { e.printStackTrace(); System.out.println(e.toString()); System.out.println(e.getMessage()); } } } Java.lang:AE:/ by Zero At test.Main() Java.lang:AE: / by Zero / by Zero
  • 20. Try with multiple catch blocks The way of handling an exception is varied from exception to exception hence for every exception type, it is highly recommended to take separate catch block that is try with multiple catch blocks is always possible and recommended to use. Example Try { Risky code; } Catch(Exception e) { } Bad programming practice
  • 21. Example: Try { Risky code; } Catch(Arithmetic Exception e) { Perform any Arithmetic operation; } Catch(FileNotFoundException e) { Use local file instead of remote file; } Catch(Exception e) { //Default Exception Handling; } Best Programming Practice
  • 22. If try with multiple catch blocks present then the order of catch blocks is very important. We have to take child first and then parent otherwise we will get compile time error saying Exception XXX has already been caught Example Try { Risky code } Catch(Exception e) { } Catch(ArithmeticException e) { } Out put : Compile time error
  • 24. Nested try Statements One try-catch block can be present in the another try’s body. This is called Nesting of try catch blocks. Each time a try block does not have a catch handler for a particular exception, the stack is unwound and the next try block’s catch handlers are inspected for a match. If no catch block matches, then the java run-time system will handle the exception.
  • 25. Syntax of Nested try Catch .... //Main try block try { statement 1; statement 2; //try-catch block inside another try block try { statement 3; statement 4; } catch(Exception e1) { //Exception Message } } catch(Exception e3) //Catch of Main(parent) try block { //Exception Message }
  • 26. Throw Keyword Some times we can create exception object explicitly and handover to jvm manually, for this we have to use throw key word. Throw new ArithmeticException(“/ by zero”); The main objective of throw key word is to handover our created exception object to jvm manually. Example Class test { Public static void main(String args[]) { Throw new ArithmeticException(“/ by zero”); } } Best use of throw keyword is for user defined exceptions or customized exceptions.
  • 27. Throws keyword In our program if there is a possibility of raising checked exception then compulsory we should handle that checked exception otherwise we will get compile time error saying Unreported Exception XXX must be caught or declared to be thrown Syntax type method-name(parameter-list) throws exception-list { // body of method } Example Class test { Public static void main(String args[]) PrintWriter pw=new PrintWriter(“abc.txt”); pw.println(“hello”); } } Compile time error: Unreported Exception java.io.FileNotFound; must be caught or declared to be thrown
  • 28. We can handle this compile time error by using Throws keyword or by using Try catch. The purpose of throws keyword is to delegate the responsibility of exception handling to the caller (it may be another method or JVM) then caller method is responsible to handle that exception Example Class test { Public static void main(String args[]) throws FileNotFoundException { PrintWriter pw=new PrintWriter(“abc.txt”); pw.println(“hello”); } }
  • 29. Throws key word requires only for checked exception. Throws key word required only to convince compiler and usage of throws keyword doesn't prevent abnormal termination of the program.
  • 30. Finally block finally block is a block that is used to execute important(clean up) code such as closing connection, stream etc. finally block is always executed whether exception is handled or not. finally block follows try or catch block. Example Try { Risky code } Catch(Exception e) { } finally { Clean up code; }
  • 33. User defined Exception subclass We can also create our own exception sub class simply by extending java Exception class. Example class TooYoungException extends RuntimeException { TooYoungException(String s) { super(s); } } class CustException { public static void main(String args[]) { int age=Integer.parseInt(args[0]); if(age<18) { throw new TooYoungException("you are too young so u r not allowed"); } else { System.out.println("u r allowed"); } } }
  • 34. Chained Exception Chained Exception was added to Java in JDK 1.4. This feature allow you to relate one exception with another exception, i.e one exception describes cause of another exception. Two new constructors and two new methods were added to Throwable class to support chained exception. Throwable( Throwable cause ) Throwable( String str, Throwable cause ) getCause() and initCause() are the two methods added to Throwable class. getCause() method returns the actual cause associated with current exception. initCause() set an underlying cause(exception) with invoking exception.
  • 35. Example import java.io.IOException; public class ChainedException { public static void divide(int a, int b) { if(b==0) { ArithmeticException ae = new ArithmeticException("top layer"); ae.initCause( new IOException("cause") ); throw ae; } else { System.out.println(a/b); } } public static void main(String[] args) { Try { divide(5, 0); } catch(ArithmeticException ae) { System.out.println( "caught : " +ae); System.out.println("actual cause: "+ae.getCause()); } } }