SlideShare a Scribd company logo
1 of 34
Exception Handling
Exception Handling
• 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.
• Exceptions can be generated by the Java run-
time system, or they can be manually
generated by your code.
• Exceptions thrown by Java relate to fundamental
errors that violate the rules of the Java language
or the constraints of the Java execution
environment.
• Manually generated exceptions are typically used
to report some error condition to the caller of a
method.
• Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally
• The general form :
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 before try block ends
}
• All exception types are subclasses of the built-
in class Throwable.
• Exception, Error are the subclasses of
Throwable class.
Exception
• This is also the class that you will subclass to
create your own custom exception types.
• Eg:
division by zero
invalid array indexing.
Error
• which defines exceptions that are not
expected to be caught under normal
circumstances by your program.
• Eg:
Stack overflow
Using try and catch
• exception handler allows you to fix the error.
Second, it prevents the program from
automatically terminating.
• To guard against and handle a run-time error,
simply enclose the code that you want to
monitor inside a try block.
• If an exception occurs within the try block, it is
thrown.
• Your code can catch this exception (using
catch) and handle it in some rational manner.
Sample
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
• Output:
Division by zero.
After catch statement.
• Once an exception is thrown, program control
transfers out of the try block into the catch
block.
• Once the catch statement has executed,
program control continues with the next line
in the program following the entire try/catch
mechanism.
• The statements that are protected by try must
be surrounded by curly braces.
Displaying a Description of an
Exception
• Throwable overrides the toString( ) method
(defined by Object) so that it returns a string
containing a description of the exception.
Multiple catch Clauses
• In some cases, more than one exception could
be raised by a single piece of code.
• To handle this type of situation, you can
specify two or more catch clauses, each
catching a different type of exception.
• After one catch statement executes, the
others are bypassed, and execution continues
after the try/catch block
Sample
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
} }
• When you use multiple catch statements, it is
important to remember that exception
subclasses must come before any of their
superclasses.
• Checked exceptions :
– Checked Exceptions forces programmers to deal
with the exception that may be thrown.
– Checked exceptions must be caught at compile
time.
• Unchecked exceptions:
– Unchecked exceptions , however, the compiler
doesn’t force the programmers to either catch the
exception or declare it in a throws clause.
Nested try Statements
• The try statement can be nested.
• Sample
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present, the following statement will
generate a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used, then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
• Output:
C:>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
throw
• It is possible for your program to throw an
exception explicitly, using the throw
statement.
• The general form :
throw ThrowableInstance;
• ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
• The flow of execution stops immediately after
the throw statement; any subsequent
statements are not executed.
• The nearest enclosing try block is inspected to
see if it has a catch statement that matches
the type of the exception.
Sample
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
} }
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.
• You do this by including a throws clause in the
method’s declaration.
• The general form:
– type method-name(parameter-list) throws
exception-list
– {
– // body of method
– }
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
} }
finally
• Any code that absolutely must be executed
before a method returns is put in a finally
block.
• The finally block will execute whether or not
an exception is thrown.
• This can be useful for closing file handles and
freeing up any other Resources.
• The finally clause is optional.
Sample
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
Java’s Built-in Exceptions
• unchecked exceptions - because the compiler
does not check to see if a method handles or
throws these exceptions.
• checked exceptions- Java defines several other
types of exceptions that relate to its various
class libraries
Unchecked Exception
Checked Exceptions
Creating Your Own Exception
Subclasses
• To create your own exception types to handle
situations specific to your applications, to do
so just define a subclass of Exception.
Sample
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
} }
Chained Exceptions
• The chained exception feature allows you to
associate another exception with an
exception.

More Related Content

What's hot

Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
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 JavaPrasad Sawant
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15Kumar
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 

What's hot (13)

Exception handling
Exception handlingException handling
Exception handling
 
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
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 

Similar to Java exception handling

Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
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 Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
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
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 

Similar to Java exception handling (20)

Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
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
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

More from GaneshKumarKanthiah (11)

Software testing regression testing
Software testing  regression testingSoftware testing  regression testing
Software testing regression testing
 
Software testing acceptance testing
Software testing  acceptance testingSoftware testing  acceptance testing
Software testing acceptance testing
 
Software testing performance testing
Software testing  performance testingSoftware testing  performance testing
Software testing performance testing
 
Software testing introduction
Software testing  introductionSoftware testing  introduction
Software testing introduction
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java packages
Java packagesJava packages
Java packages
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java interface
Java interfaceJava interface
Java interface
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java awt
Java awtJava awt
Java awt
 
Java applet
Java appletJava applet
Java applet
 

Recently uploaded

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
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
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
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
 
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
 

Recently uploaded (20)

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
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...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
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...
 
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
 

Java exception handling

  • 2. Exception Handling • 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. • Exceptions can be generated by the Java run- time system, or they can be manually generated by your code.
  • 3. • Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. • Manually generated exceptions are typically used to report some error condition to the caller of a method. • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally
  • 4. • The general form : 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 before try block ends }
  • 5. • All exception types are subclasses of the built- in class Throwable. • Exception, Error are the subclasses of Throwable class.
  • 6. Exception • This is also the class that you will subclass to create your own custom exception types. • Eg: division by zero invalid array indexing.
  • 7. Error • which defines exceptions that are not expected to be caught under normal circumstances by your program. • Eg: Stack overflow
  • 8. Using try and catch • exception handler allows you to fix the error. Second, it prevents the program from automatically terminating. • To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block.
  • 9. • If an exception occurs within the try block, it is thrown. • Your code can catch this exception (using catch) and handle it in some rational manner.
  • 10. Sample class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } }
  • 11. • Output: Division by zero. After catch statement. • Once an exception is thrown, program control transfers out of the try block into the catch block. • Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
  • 12. • The statements that are protected by try must be surrounded by curly braces.
  • 13. Displaying a Description of an Exception • Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception.
  • 14. Multiple catch Clauses • In some cases, more than one exception could be raised by a single piece of code. • To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. • After one catch statement executes, the others are bypassed, and execution continues after the try/catch block
  • 15. Sample class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } }
  • 16. • When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses.
  • 17. • Checked exceptions : – Checked Exceptions forces programmers to deal with the exception that may be thrown. – Checked exceptions must be caught at compile time. • Unchecked exceptions: – Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause.
  • 18. Nested try Statements • The try statement can be nested. • Sample class NestTry { public static void main(String args[]) { try { int a = args.length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero
  • 19. /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } }
  • 20. • Output: C:>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One a = 1 Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException
  • 21. throw • It is possible for your program to throw an exception explicitly, using the throw statement. • The general form : throw ThrowableInstance; • ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
  • 22. • The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. • The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception.
  • 23. Sample class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
  • 24. 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. • You do this by including a throws clause in the method’s declaration. • The general form: – type method-name(parameter-list) throws exception-list – { – // body of method – }
  • 25. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } }
  • 26. finally • Any code that absolutely must be executed before a method returns is put in a finally block. • The finally block will execute whether or not an exception is thrown. • This can be useful for closing file handles and freeing up any other Resources. • The finally clause is optional.
  • 27. Sample class FinallyDemo { // Through an exception out of the method. static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } }
  • 28. Java’s Built-in Exceptions • unchecked exceptions - because the compiler does not check to see if a method handles or throws these exceptions. • checked exceptions- Java defines several other types of exceptions that relate to its various class libraries
  • 31. Creating Your Own Exception Subclasses • To create your own exception types to handle situations specific to your applications, to do so just define a subclass of Exception.
  • 32. Sample class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } } class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")");
  • 33. if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } }
  • 34. Chained Exceptions • The chained exception feature allows you to associate another exception with an exception.