SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Programming in Java
Lecture 14: Exception Handling
By
Ravi Kant Sahu
Asst. Professor
Lovely Professional University, PunjabLovely Professional University, Punjab
ExcEption
Introduction
• An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's
instructions.
• A Java exception is an object that describes an exceptional (that
is, error) condition that has occurred in a piece of code.
• An exception is an abnormal condition that arises in a code
sequence at run time.
• In other words, an exception is a run-time error.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exception Handling
class Exception
{
public static void main (String arr[])
{
System.out.println(“Enter two numbers”);
Scanner s = new Scanner (System.in);
int x = s.nextInt();
int y = s.nextInt();
int z = x/y;
System.out.println(“result of division is : ” + z);
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exception Handling
• An Exception is a run-time error that can be handled
programmatically in the application and does not result in
abnormal program termination.
• Exception handling is a mechanism that facilitates
programmatic handling of run-time errors.
• In java, each run-time error is represented by an object.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exception (Class Hierarchy)
• At the root of the class hierarchy, there is an abstract class named
‘Throwable’which represents the basic features of run-time errors.
• There are two non-abstract sub-classes of Throwable.
• Exception : can be handled
• Error : can’t be handled
• RuntimeException is the sub-class of Exception.
• Exceptions of this type are automatically defined for the programs
that we write and include things such as division by zero and invalid
array indexing.
• Each exception is a run-time error but all run-time errors are not
exceptions.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Throwable
Exception Error
Run-time Exception - VirtualMachine
• IOEXception - ArithmeticException - NoSuchMethod
• SQLException - ArrayIndexOutOf - StackOverFlow
BoundsException
- NullPointerException
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Checked Exception
Unchecked Exception
Checked Exception
• Checked Exceptions are those, that have to be either caught or
declared to be thrown in the method in which they are raised.
Unchecked Exception
• Unchecked Exceptions are those that are not forced by the
compiler either to be caught or to be thrown.
• Unchecked Exceptions either represent common programming
errors or those run-time errors that can’t be handled through
exception handling.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Commonly used sub-classes of Exception
• ArithmeticException
• ArrayIndexOutOfBoundsException
• NumberFormatException
• NullPointerException
• IOException
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Commonly used sub-classes of Errors
• VirualMachineError
• StackOverFlowError
• NoClassDefFoundError
• NoSuchMethodError
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Uncaught Exceptions
class Exception_Demo
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
• When the Java run-time system detects the attempt to divide by
zero, it constructs a new exception object and then throws this
exception.
• once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• In the previous example, we haven’t supplied any exception
handlers of our own.
• So the exception is caught by the default handler provided by the
Java run-time system.
• Any exception that is not caught by your program will ultimately be
processed by the default handler.
• The default handler displays a string describing the exception, prints
a stack trace from the point at which the exception occurred, and
terminates the program.
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why Exception Handling?
• When the default exception handler is provided by the Java
run-time system , why Exception Handling?
• Exception Handling is needed because:
– it allows to fix the error, customize the message .
– it prevents the program from automatically terminating
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ExcEption Handling
Keywords for Exception Handling
• try
• catch
• throw
• throws
• finally
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
try
• used to execute the statements whose execution may result in
an exception.
try {
Statements whose execution may cause an exception
}
Note: try block is always used either with catch or finally or with
both.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
catch
• catch is used to define a handler.
• It contains statements that are to be executed when the
exception represented by the catch block is generated.
• If program executes normally, then the statements of catch
block will not executed.
• If no catch block is found in program, exception is caught by
JVM and program is terminated.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Divide{
public static void main(String arr[]){
try {
int a= Integer.parseInt(arr[0]);
int b= Integer.parseInt(arr[1]);
int c = a/b;
System.out.println(“Result is: ”+c);
}
catch (ArithmeticException e)
{System.out.println(“Second number must be non-zero”);}
catch (NumberFormatException n)
{System.out.println(“Arguments must be Numeric”);}
catch (ArrayIndexOutOfBoundsException a)
{System.out.println(“Invalid Number of arguments”);}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Nested Try’s
class NestedTryDemo {
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
}
catch (ArithmeticException e)
{
System.out.println(“Div by zero error!");
}
}
catch (ArrayIndexOutOfBoundsException) {
System.out.println(“Need 2 parameters!");
}
}}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Defining Generalized Exception Handler
• A generalized exception handler is one that can handle the
exceptions of all types.
• If a class has a generalized as well as specific exception
handler, then the generalized exception handler must be the
last one.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Divide{
public static void main(String arr[]){
try {
int a= Integer.parseInt(arr[0]);
int b= Integer.parseInt(arr[1]);
int c = a/b;
System.out.println(“Result is: ”+c);
}
catch (Throwable e)
{
System.out.println(e);
}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
throw
• used for explicit exception throwing.
throw(Exception obj);
‘throw’ keyword can be used:
• to throw user defined exception
• to customize the message to be displayed by predefined exceptions
• to re-throw a caught exception
• Note: System-generated exceptions are automatically thrown by
the Java run-time system.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class ThrowDemo
{
static void demo()
{
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demo.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try {
demo();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
throws
• A throws clause lists the types of exceptions that a method might
throw.
type method-name(parameter-list) throws exception-list
{
// body of method
}
• This is necessary for all exceptions, except those of type Error or
Runtime Exception, or any of their subclasses.
• All other exceptions that a method can throw must be declared in
the throws clause. If they are not, a compile-time error will result.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
import java.io.*;
public class ThrowsDemo
{
public static void main( String args []) throws IOException
{
char i;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter character, 'q' to quit");
do{
i = (char) br.read();
System.out.print(i);
}while(i!='q');
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
Finally
• finally creates a block of code that will be executed after a
try/catch block has completed and before the code following
the try/catch block.
• The finally block will execute whether or not an exception is
thrown.
• If an exception is thrown, the finally block will execute even if
no catch statement matches the exception.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• If a finally block is associated with a try, the finally block will
be executed upon conclusion of the try.
• The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Chained Exceptions
• Throwing an exception along with another exception forms a
chained exception.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Chained Exceptions
public class ChainedExceptionDemo {
public static void main(String[] args) {
try { method1(); }
catch (Exception ex) { ex.printStackTrace();} }
public static void method1() throws Exception {
try { method2(); }
catch (Exception ex) {
throw new Exception("New info from method1”, ex); } }
public static void method2() throws Exception {
throw new Exception("New info from method2");
} }
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Defining Custom Exceptions
• We can create our own Exception sub-classes by inheriting
Exception class.
• The Exception class does not define any methods of its own.
• It inherits those methods provided by Throwable.
• Thus, all exceptions, including those that we create, have the
methods defined by Throwable available to them.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructor for creating Exception
• Exception( )
• Exception(String msg)
• A custom exception class is represented by a subclass of
Exception / Throwable.
• It contains the above mentioned constructor to initialize
custom exception object.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Myexception extends Throwable
{
public Myexception(int i)
{
System.out.println("you have entered ." +i +" : It exceeding
the limit");
}
}
public class ExceptionTest {
public void show(int i) throws Myexception {
if(i>100)
throw new Myexception(i);
else
System.out.println(+i+" is less then 100 it is ok");
}
public static void main(String []args){
int i=Integer.parseInt(args[0]);
int j=Integer.parseInt(args[1]);
ExceptionTest t=new ExceptionTest();
try{
t.show(i); t.show(j);
}
catch(Throwable e) {
System.out.println("catched exception is "+e);
}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

Mais conteúdo relacionado

Mais procurados

Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questionsrithustutorials
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsGanesh Samarthyam
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterJAXLondon2014
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 

Mais procurados (20)

Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Gui programming (awt)
Gui programming (awt)Gui programming (awt)
Gui programming (awt)
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questions
 
Java Basics
Java BasicsJava Basics
Java Basics
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Core java
Core javaCore java
Core java
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
Core Java
Core JavaCore Java
Core Java
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
Spring boot
Spring bootSpring boot
Spring boot
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 

Destaque (18)

Event handling
Event handlingEvent handling
Event handling
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Internationalization
InternationalizationInternationalization
Internationalization
 
Servlets
ServletsServlets
Servlets
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Array
ArrayArray
Array
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Java Inner Classes
Java Inner ClassesJava Inner Classes
Java Inner Classes
 
Basic IO
Basic IOBasic IO
Basic IO
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Packages
PackagesPackages
Packages
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 

Semelhante a Exception handling

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptpromila09
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Errors and exception
Errors and exceptionErrors and exception
Errors and exceptionRishav Upreti
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javachauhankapil
 

Semelhante a Exception handling (20)

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Introduction to java programming part 2
Introduction to java programming  part 2Introduction to java programming  part 2
Introduction to java programming part 2
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Errors and exception
Errors and exceptionErrors and exception
Errors and exception
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 

Último

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Último (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Exception handling

  • 1. Programming in Java Lecture 14: Exception Handling By Ravi Kant Sahu Asst. Professor Lovely Professional University, PunjabLovely Professional University, Punjab
  • 3. Introduction • An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. • A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. • An exception is an abnormal condition that arises in a code sequence at run time. • In other words, an exception is a run-time error. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Exception Handling class Exception { public static void main (String arr[]) { System.out.println(“Enter two numbers”); Scanner s = new Scanner (System.in); int x = s.nextInt(); int y = s.nextInt(); int z = x/y; System.out.println(“result of division is : ” + z); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Exception Handling • An Exception is a run-time error that can be handled programmatically in the application and does not result in abnormal program termination. • Exception handling is a mechanism that facilitates programmatic handling of run-time errors. • In java, each run-time error is represented by an object. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Exception (Class Hierarchy) • At the root of the class hierarchy, there is an abstract class named ‘Throwable’which represents the basic features of run-time errors. • There are two non-abstract sub-classes of Throwable. • Exception : can be handled • Error : can’t be handled • RuntimeException is the sub-class of Exception. • Exceptions of this type are automatically defined for the programs that we write and include things such as division by zero and invalid array indexing. • Each exception is a run-time error but all run-time errors are not exceptions. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. Throwable Exception Error Run-time Exception - VirtualMachine • IOEXception - ArithmeticException - NoSuchMethod • SQLException - ArrayIndexOutOf - StackOverFlow BoundsException - NullPointerException Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) Checked Exception Unchecked Exception
  • 8. Checked Exception • Checked Exceptions are those, that have to be either caught or declared to be thrown in the method in which they are raised. Unchecked Exception • Unchecked Exceptions are those that are not forced by the compiler either to be caught or to be thrown. • Unchecked Exceptions either represent common programming errors or those run-time errors that can’t be handled through exception handling. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. Commonly used sub-classes of Exception • ArithmeticException • ArrayIndexOutOfBoundsException • NumberFormatException • NullPointerException • IOException Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Commonly used sub-classes of Errors • VirualMachineError • StackOverFlowError • NoClassDefFoundError • NoSuchMethodError Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Uncaught Exceptions class Exception_Demo { public static void main(String args[]) { int d = 0; int a = 42 / d; } } • When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. • once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. • In the previous example, we haven’t supplied any exception handlers of our own. • So the exception is caught by the default handler provided by the Java run-time system. • Any exception that is not caught by your program will ultimately be processed by the default handler. • The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Why Exception Handling? • When the default exception handler is provided by the Java run-time system , why Exception Handling? • Exception Handling is needed because: – it allows to fix the error, customize the message . – it prevents the program from automatically terminating Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. Keywords for Exception Handling • try • catch • throw • throws • finally Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Keywords for Exception Handling try • used to execute the statements whose execution may result in an exception. try { Statements whose execution may cause an exception } Note: try block is always used either with catch or finally or with both. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. Keywords for Exception Handling catch • catch is used to define a handler. • It contains statements that are to be executed when the exception represented by the catch block is generated. • If program executes normally, then the statements of catch block will not executed. • If no catch block is found in program, exception is caught by JVM and program is terminated. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. class Divide{ public static void main(String arr[]){ try { int a= Integer.parseInt(arr[0]); int b= Integer.parseInt(arr[1]); int c = a/b; System.out.println(“Result is: ”+c); } catch (ArithmeticException e) {System.out.println(“Second number must be non-zero”);} catch (NumberFormatException n) {System.out.println(“Arguments must be Numeric”);} catch (ArrayIndexOutOfBoundsException a) {System.out.println(“Invalid Number of arguments”);} } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. Nested Try’s class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); try { int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Div by zero error!"); } } catch (ArrayIndexOutOfBoundsException) { System.out.println(“Need 2 parameters!"); } }} Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. Defining Generalized Exception Handler • A generalized exception handler is one that can handle the exceptions of all types. • If a class has a generalized as well as specific exception handler, then the generalized exception handler must be the last one. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. class Divide{ public static void main(String arr[]){ try { int a= Integer.parseInt(arr[0]); int b= Integer.parseInt(arr[1]); int c = a/b; System.out.println(“Result is: ”+c); } catch (Throwable e) { System.out.println(e); } } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. Keywords for Exception Handling throw • used for explicit exception throwing. throw(Exception obj); ‘throw’ keyword can be used: • to throw user defined exception • to customize the message to be displayed by predefined exceptions • to re-throw a caught exception • Note: System-generated exceptions are automatically thrown by the Java run-time system. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. class ThrowDemo { static void demo() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demo."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demo(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. Keywords for Exception Handling throws • A throws clause lists the types of exceptions that a method might throw. type method-name(parameter-list) throws exception-list { // body of method } • This is necessary for all exceptions, except those of type Error or Runtime Exception, or any of their subclasses. • All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. import java.io.*; public class ThrowsDemo { public static void main( String args []) throws IOException { char i; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter character, 'q' to quit"); do{ i = (char) br.read(); System.out.print(i); }while(i!='q'); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 26. Keywords for Exception Handling Finally • finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. • The finally block will execute whether or not an exception is thrown. • If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. • If a finally block is associated with a try, the finally block will be executed upon conclusion of the try. • The finally clause is optional. However, each try statement requires at least one catch or a finally clause. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. Chained Exceptions • Throwing an exception along with another exception forms a chained exception. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. Chained Exceptions public class ChainedExceptionDemo { public static void main(String[] args) { try { method1(); } catch (Exception ex) { ex.printStackTrace();} } public static void method1() throws Exception { try { method2(); } catch (Exception ex) { throw new Exception("New info from method1”, ex); } } public static void method2() throws Exception { throw new Exception("New info from method2"); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. Defining Custom Exceptions • We can create our own Exception sub-classes by inheriting Exception class. • The Exception class does not define any methods of its own. • It inherits those methods provided by Throwable. • Thus, all exceptions, including those that we create, have the methods defined by Throwable available to them. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 31. Constructor for creating Exception • Exception( ) • Exception(String msg) • A custom exception class is represented by a subclass of Exception / Throwable. • It contains the above mentioned constructor to initialize custom exception object. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 32. class Myexception extends Throwable { public Myexception(int i) { System.out.println("you have entered ." +i +" : It exceeding the limit"); } }
  • 33. public class ExceptionTest { public void show(int i) throws Myexception { if(i>100) throw new Myexception(i); else System.out.println(+i+" is less then 100 it is ok"); } public static void main(String []args){ int i=Integer.parseInt(args[0]); int j=Integer.parseInt(args[1]); ExceptionTest t=new ExceptionTest(); try{ t.show(i); t.show(j); } catch(Throwable e) { System.out.println("catched exception is "+e); } } }
  • 34. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)