SlideShare a Scribd company logo
Exception Handling In Java
Catch
Throw
BY NEHA KUAMRI
Exception
 Exception is an abnormal condition that
arises at run time.
 Event that disrupts the normal flow of
the program.
 It is an object which is thrown at runtime.
Exception Handling
 Exception Handling is a mechanism to
handle runtime errors.
 Normal flow of the application can be
maintained.
 It is an object which is thrown at runtime.
 Exception handling done with the
exception object.
Types of Errors
There are three categories of errors:
 Syntax errors - arise because the rules of the language have not been followed. They
are detected by the compiler.
 Runtime errors – occur while the program is running if the environment detects an
operation that is impossible to carry out.
 Logic errors – occur when a program doesn’t perform the way it was intended to.
Types of Exception
• There are mainly two types of exceptions:
• Checked
• Unchecked – E.g. error
• The sun microsystem says there are three types of exceptions:
• Checked Exception – are checked at compile-time.
• Unchecked Exception – are not checked at compile-time rather they are
checked at runtime.
• Error
Checked Exception
• Classes that extends Throwable class RuntimeException and Error are known as
checked exceptions. Checked Exception means that compiler forces the programmer to
check and deal with the exceptions. e.g. IOException, SQLException etc.
Unchecked Exception
• Classes that extends RuntimeException, Error and their subclasses are known as
unchecked exceptions e.g. ArithmeticException, NullPointerException etc.
Error
• Error is irrecoverable should not try to catch. e.g. OutOfMemoryError,
VirtualMachineError etc.
Exception Classes
Object Throwable
Exception
ClassNotFoundException
IOException
AWTException
RuntimeException
ArithmeticException
NullPointerException
IndexOutOfBoundException
IllegalArgumentException
Several more classes
Several more
classes
Error
LinkageError
VirtualMachineError
AWTError
Several more classes
System Errors
Object Throwable
Exception
ClassNotFoundException
IOException
AWTException
RuntimeException
ArithmeticException
NullPointerException
IndexOutOfBoundException
IllegalArgumentException
Several more
classes
Several more
classes
Error
LinkageError
VirtualMachineError
AWTError
Several more
classes
System errors are thrown by JVM
and represented in the Error
class. The Error class describes
internal system errors. Such
errors rarely occur.
Exceptions
Object Throwable
Exception
ClassNotFoundException
IOException
AWTException
RuntimeException
ArithmeticException
NullPointerException
IndexOutOfBoundException
IllegalArgumentException
Several more
classes
Several more
classes
Error
LinkageError
VirtualMachineError
AWTError
Several more
classes
Exception describes errors
caused by your program and
external circumstances. These
errors can caught and handled by
your program.
Runtime Exceptions
Object Throwable
Exception
ClassNotFoundException
IOException
AWTException
RuntimeException
ArithmeticException
NullPointerException
IndexOutOfBoundException
IllegalArgumentException
Several more
classes
Several more
classes
Error
LinkageError
VirtualMachineError
AWTError
Several more
classes
RuntimeException is caused by
programming errors, such as bad
casting, numeric errors etc.
Exception Handling Terms
• try – used to enclose a segment of code that may produce a exception.
• catch – placed directly after the try block to handle one or more exception
types.
• Throw – to generate an exception or to describe an instance of an
exception.
• finally – optional statement used after a try-catch block to run a segment of
code regardless if exception is generated.
Exceptions - Syntax
try{
//code which might throw an exception
}
catch(ExceptionClass object1){
//code to handle an exception
}
catch(ExceptionClass object2){
//code to handle an exception
}
finally{
//ALWAYS EXCEUTED WHETHER AN EXCETPTION WAS THROWN OR NOT
}
Class A{
public static void main(String args[]){
int data=50/0;
System.out.println(“Rest of the code….”);
}
}
Output:
Exception in thread main java.lang.ArithemeticException:/by zero Rest of the
code is not executed (rest of the code…) statement is not printed.
Example 1.
 Java Virtual Machine (JVM) first checks whether the exception is handled
or not.
 If exception is not handled, JVM provides a default exception handler that
performs the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Cause the program to terminate.
 If exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
Example 2.
Class A{
Public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){
System.out.println(e);
}System.out.println(“rest of the code…”);
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/by zero rest of the code….
Multiple catch block:
• If more than one exception can occur, then we use multiple catch blocks.
• When an exception is thrown, each catch statements is inspected in order,
and the first one whose type matches that of the exception is executed.
• After one catch statement executes, the other are bypassed
Multiple Catch Exceptions - Syntax
Try{
//code which might throw an exception
}
Catch(ExceptionClass object1){
//code to handle an exception
}
Catch(ExceptionClass object2){
//code to handle an exception
}
Nested try Statements
• A try statement can be inside the block of another try.
• Each time a try statement is entered, the context of that exception is
pushed on the stack.
• If an inner try statement does not have a catch, then the next try
statement’s catch handlers are inspected for a match.
• If a method call within a try block has try block within it, then it is still nested
try.
Nested try block
Try{
statement 1;
statement 2;
try{
statement 1;
statement 2;
}catch(Exception e){…..}
}catch(Exception e){……}
Example 3.
Class A{
public static void main(String args[]){
try{
try{
System.out.println(“going to divide”);
int b=39/0;
}catch(ArithmeticException e){
System.out.println(e);
}try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundException e){
System.out.println(e);
} System.out.println(“other statement”);
}catch(Exception e){
System.out.println(“handled”);
} System.out.println(“normal flow…”);
}
}
Finally block
 Finally block is a block that is always executed.
 To perform some important tasks such as closing connection, stream etc.
 Used to put “cleanup” code such as closing a file, closing connection etc.
 Finally creates a block of code that will be executed after a try/catch block has completed.
 Finally block will be executed whether or not an exception is thrown.
 Each try clause requires at least one catch or finally clause.
 Note: Before terminating the program, JVM executes finally clock (if any).
 Note: finally must be followed by try or catch block.
Exception
occurred?
Program code
Exception
handled?
Finally block is executed
no yes
no yes
Example 4.
Class A{
Public static void main(String args[]){
try{
int data=25/0;
System.out.println(“data”);
}catch(ArithmeticException e){
System.out.println(e);
}finally{
System.out.println(“rest of the code…”);
}
}
Throw keyword
• Throw keyword is a keyword used to explicitly throw an exception / custom
exception.
throw new ExceptionName(“Error Message”);
• Throw either checked or unchecked exception.
throw new ThrowbleInstance
• ThrowableInstance must be an object of type Throwable / subclass Throwable
• There are two ways to obtain a Throwable objects:
• Using a parameter into a catch clause.
• Creating one with the new operator.
Example 5.
public class bank{
public static void main(String args[]){
int balance = 100, withdraw = 1000;
if(balance<withdraw){
//ArithmeticException e = new ArithmeticException(No money please”);
//throw r;
//throw new ArithmeticException(“No Money”);
}else{
System.out.println(“Draw & enjoy Sir/Mam, Best wishes of the day”);
}
}
}
Example 6.
Import java.io.*;
Public class Example{
public static void main(String args[]) throws IOException{
DataInputStream dis = new DataInputStream(System.in);
int x = Integer.parseInt(dis.readLine());
if(x<0){
throw new illegalArgumentException();
throw new illegalArgumentException(“You have entered no”+””+ x +””+”which is less than 0”);
}else{
System.out.println(“The no is “+x);
}
}
}
throws
• If a method is capable of causing an exception that it does not handle, it must specify this
behaviour so that callers of the method can guard themselves against that exception.
Type method-name (parameter-list) throws exception-list{
//body of method
}
• It is not applicable for Error or RuntimeException, or any of their subclasses.
Error: beyond your control e.g. you are unable
to do anything.
E.g.
VirtualMachineError or StackOverFlowError.
Throw keyword
• Throw is used to explicitly throw an
exception.
• Checked exception can not be
propagated without throws.
• Throw is followed by an instance.
• Throw is used within the method.
• You cannot throw multiple exception.
Throws keyword
• Throws is used to declare an exception.
• Checked exception can be propagated
with throws.
• Throws is followed by class.
• Throws is used with the method signature.
• You can declare multiple exception e.g.
public void method() throws IOException,
SQLException.
Unchecked Exception:
under your control so correct your code.
Create Our Own Exception
Class NumberRangeException extends Exception{
String msg;
NumberRangeException(){
msg = new String(“Enter a number between 20 and 100”);
}
}
Public class My_Exception{
public static void main(String args[]){
try{
int x = 10;
if(x < 20 || x > 100) throw new NumberRangeException();
}catch(NumberRangeException e){
System.out.println(e);
}
}
}
Thank You…
All Content Written By Neha Kumari
Ad

More Related Content

What's hot (20)

Java Annotations
Java AnnotationsJava Annotations
Java Annotations
Serhii Kartashov
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in Angular
Knoldus Inc.
 
Handling iframes using selenium web driver
Handling iframes using selenium web driverHandling iframes using selenium web driver
Handling iframes using selenium web driver
Pankaj Biswas
 
Testing Spring Boot Applications
Testing Spring Boot ApplicationsTesting Spring Boot Applications
Testing Spring Boot Applications
VMware Tanzu
 
Packages in java
Packages in javaPackages in java
Packages in java
Kavitha713564
 
Test Case Creation in Katalon Studio
Test Case Creation in Katalon StudioTest Case Creation in Katalon Studio
Test Case Creation in Katalon Studio
RapidValue
 
Spring Security
Spring SecuritySpring Security
Spring Security
Knoldus Inc.
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
Andrii Lundiak
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
José Paumard
 
PHPUnit - Unit testing
PHPUnit - Unit testingPHPUnit - Unit testing
PHPUnit - Unit testing
Nguyễn Đào Thiên Thư
 
05 junit
05 junit05 junit
05 junit
mha4
 
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Caelum
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
Eduardo Carvalho
 
Dependency injection in CakePHP
Dependency injection in CakePHPDependency injection in CakePHP
Dependency injection in CakePHP
markstory
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
Richard North
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
Michael Heron
 
Spring boot
Spring bootSpring boot
Spring boot
Bhagwat Kumar
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in Angular
Knoldus Inc.
 
Handling iframes using selenium web driver
Handling iframes using selenium web driverHandling iframes using selenium web driver
Handling iframes using selenium web driver
Pankaj Biswas
 
Testing Spring Boot Applications
Testing Spring Boot ApplicationsTesting Spring Boot Applications
Testing Spring Boot Applications
VMware Tanzu
 
Test Case Creation in Katalon Studio
Test Case Creation in Katalon StudioTest Case Creation in Katalon Studio
Test Case Creation in Katalon Studio
RapidValue
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
Andrii Lundiak
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
José Paumard
 
05 junit
05 junit05 junit
05 junit
mha4
 
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Caelum
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Dependency injection in CakePHP
Dependency injection in CakePHPDependency injection in CakePHP
Dependency injection in CakePHP
markstory
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
Richard North
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
Michael Heron
 

Similar to Exception Handling In Java Presentation. 2024 (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
Bharat17485
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
Bharat17485
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Ad

Recently uploaded (20)

Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Ad

Exception Handling In Java Presentation. 2024

  • 1. Exception Handling In Java Catch Throw BY NEHA KUAMRI
  • 2. Exception  Exception is an abnormal condition that arises at run time.  Event that disrupts the normal flow of the program.  It is an object which is thrown at runtime. Exception Handling  Exception Handling is a mechanism to handle runtime errors.  Normal flow of the application can be maintained.  It is an object which is thrown at runtime.  Exception handling done with the exception object.
  • 3. Types of Errors There are three categories of errors:  Syntax errors - arise because the rules of the language have not been followed. They are detected by the compiler.  Runtime errors – occur while the program is running if the environment detects an operation that is impossible to carry out.  Logic errors – occur when a program doesn’t perform the way it was intended to.
  • 4. Types of Exception • There are mainly two types of exceptions: • Checked • Unchecked – E.g. error • The sun microsystem says there are three types of exceptions: • Checked Exception – are checked at compile-time. • Unchecked Exception – are not checked at compile-time rather they are checked at runtime. • Error
  • 5. Checked Exception • Classes that extends Throwable class RuntimeException and Error are known as checked exceptions. Checked Exception means that compiler forces the programmer to check and deal with the exceptions. e.g. IOException, SQLException etc. Unchecked Exception • Classes that extends RuntimeException, Error and their subclasses are known as unchecked exceptions e.g. ArithmeticException, NullPointerException etc. Error • Error is irrecoverable should not try to catch. e.g. OutOfMemoryError, VirtualMachineError etc.
  • 7. System Errors Object Throwable Exception ClassNotFoundException IOException AWTException RuntimeException ArithmeticException NullPointerException IndexOutOfBoundException IllegalArgumentException Several more classes Several more classes Error LinkageError VirtualMachineError AWTError Several more classes System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur.
  • 8. Exceptions Object Throwable Exception ClassNotFoundException IOException AWTException RuntimeException ArithmeticException NullPointerException IndexOutOfBoundException IllegalArgumentException Several more classes Several more classes Error LinkageError VirtualMachineError AWTError Several more classes Exception describes errors caused by your program and external circumstances. These errors can caught and handled by your program.
  • 9. Runtime Exceptions Object Throwable Exception ClassNotFoundException IOException AWTException RuntimeException ArithmeticException NullPointerException IndexOutOfBoundException IllegalArgumentException Several more classes Several more classes Error LinkageError VirtualMachineError AWTError Several more classes RuntimeException is caused by programming errors, such as bad casting, numeric errors etc.
  • 10. Exception Handling Terms • try – used to enclose a segment of code that may produce a exception. • catch – placed directly after the try block to handle one or more exception types. • Throw – to generate an exception or to describe an instance of an exception. • finally – optional statement used after a try-catch block to run a segment of code regardless if exception is generated.
  • 11. Exceptions - Syntax try{ //code which might throw an exception } catch(ExceptionClass object1){ //code to handle an exception } catch(ExceptionClass object2){ //code to handle an exception } finally{ //ALWAYS EXCEUTED WHETHER AN EXCETPTION WAS THROWN OR NOT }
  • 12. Class A{ public static void main(String args[]){ int data=50/0; System.out.println(“Rest of the code….”); } } Output: Exception in thread main java.lang.ArithemeticException:/by zero Rest of the code is not executed (rest of the code…) statement is not printed. Example 1.
  • 13.  Java Virtual Machine (JVM) first checks whether the exception is handled or not.  If exception is not handled, JVM provides a default exception handler that performs the following tasks:  Prints out exception description.  Prints the stack trace (Hierarchy of methods where the exception occurred).  Cause the program to terminate.  If exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
  • 14. Example 2. Class A{ Public static void main(String args[]){ try{ int data=50/0; }catch(ArithmeticException e){ System.out.println(e); }System.out.println(“rest of the code…”); } } Output: Exception in thread main java.lang.ArithmeticException:/by zero rest of the code….
  • 15. Multiple catch block: • If more than one exception can occur, then we use multiple catch blocks. • When an exception is thrown, each catch statements is inspected in order, and the first one whose type matches that of the exception is executed. • After one catch statement executes, the other are bypassed
  • 16. Multiple Catch Exceptions - Syntax Try{ //code which might throw an exception } Catch(ExceptionClass object1){ //code to handle an exception } Catch(ExceptionClass object2){ //code to handle an exception }
  • 17. Nested try Statements • A try statement can be inside the block of another try. • Each time a try statement is entered, the context of that exception is pushed on the stack. • If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match. • If a method call within a try block has try block within it, then it is still nested try.
  • 18. Nested try block Try{ statement 1; statement 2; try{ statement 1; statement 2; }catch(Exception e){…..} }catch(Exception e){……}
  • 19. Example 3. Class A{ public static void main(String args[]){ try{ try{ System.out.println(“going to divide”); int b=39/0; }catch(ArithmeticException e){ System.out.println(e); }try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundException e){ System.out.println(e); } System.out.println(“other statement”); }catch(Exception e){ System.out.println(“handled”); } System.out.println(“normal flow…”); } }
  • 20. Finally block  Finally block is a block that is always executed.  To perform some important tasks such as closing connection, stream etc.  Used to put “cleanup” code such as closing a file, closing connection etc.  Finally creates a block of code that will be executed after a try/catch block has completed.  Finally block will be executed whether or not an exception is thrown.  Each try clause requires at least one catch or finally clause.  Note: Before terminating the program, JVM executes finally clock (if any).  Note: finally must be followed by try or catch block.
  • 22. Example 4. Class A{ Public static void main(String args[]){ try{ int data=25/0; System.out.println(“data”); }catch(ArithmeticException e){ System.out.println(e); }finally{ System.out.println(“rest of the code…”); } }
  • 23. Throw keyword • Throw keyword is a keyword used to explicitly throw an exception / custom exception. throw new ExceptionName(“Error Message”); • Throw either checked or unchecked exception. throw new ThrowbleInstance • ThrowableInstance must be an object of type Throwable / subclass Throwable • There are two ways to obtain a Throwable objects: • Using a parameter into a catch clause. • Creating one with the new operator.
  • 24. Example 5. public class bank{ public static void main(String args[]){ int balance = 100, withdraw = 1000; if(balance<withdraw){ //ArithmeticException e = new ArithmeticException(No money please”); //throw r; //throw new ArithmeticException(“No Money”); }else{ System.out.println(“Draw & enjoy Sir/Mam, Best wishes of the day”); } } }
  • 25. Example 6. Import java.io.*; Public class Example{ public static void main(String args[]) throws IOException{ DataInputStream dis = new DataInputStream(System.in); int x = Integer.parseInt(dis.readLine()); if(x<0){ throw new illegalArgumentException(); throw new illegalArgumentException(“You have entered no”+””+ x +””+”which is less than 0”); }else{ System.out.println(“The no is “+x); } } }
  • 26. throws • If a method is capable of causing an exception that it does not handle, it must specify this behaviour so that callers of the method can guard themselves against that exception. Type method-name (parameter-list) throws exception-list{ //body of method } • It is not applicable for Error or RuntimeException, or any of their subclasses.
  • 27. Error: beyond your control e.g. you are unable to do anything. E.g. VirtualMachineError or StackOverFlowError. Throw keyword • Throw is used to explicitly throw an exception. • Checked exception can not be propagated without throws. • Throw is followed by an instance. • Throw is used within the method. • You cannot throw multiple exception. Throws keyword • Throws is used to declare an exception. • Checked exception can be propagated with throws. • Throws is followed by class. • Throws is used with the method signature. • You can declare multiple exception e.g. public void method() throws IOException, SQLException. Unchecked Exception: under your control so correct your code.
  • 28. Create Our Own Exception Class NumberRangeException extends Exception{ String msg; NumberRangeException(){ msg = new String(“Enter a number between 20 and 100”); } }
  • 29. Public class My_Exception{ public static void main(String args[]){ try{ int x = 10; if(x < 20 || x > 100) throw new NumberRangeException(); }catch(NumberRangeException e){ System.out.println(e); } } }
  • 30. Thank You… All Content Written By Neha Kumari