SlideShare a Scribd company logo
1 of 34
Programming in Java
Lecture 14: Exception Handling
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.
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);
}
}
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.
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.
Throwable
Exception Error
Run-time Exception - VirtualMachine
• IOEXception - ArithmeticException - NoSuchMethod
• SQLException - ArrayIndexOutOf - StackOverFlow
BoundsException
- NullPointerException
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.
Commonly used sub-classes of Exception
• ArithmeticException
• ArrayIndexOutOfBoundsException
• NumberFormatException
• NullPointerException
• IOException
Commonly used sub-classes of Errors
• VirualMachineError
• StackOverFlowError
• NoClassDefFoundError
• NoSuchMethodError
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.
• 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)
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
Exception Handling
Keywords for Exception Handling
• try
• catch
• throw
• throws
• finally
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.
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.
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”);}
}
}
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!");
}
}}
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.
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);
}
}
}
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.
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);
}
}
}
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.
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');
}
}
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.
• 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.
Chained Exceptions
• Throwing an exception along with another exception forms a
chained exception.
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");
} }
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.
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.
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);
}
}
}
L14 exception handling

More Related Content

What's hot

Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 

What's hot (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
C# String
C# StringC# String
C# String
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Data types in java
Data types in javaData types in java
Data types in java
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Inline function
Inline functionInline function
Inline function
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 

Viewers also liked (8)

Java: Exception Handling
Java: Exception HandlingJava: Exception Handling
Java: Exception Handling
 
Um presentation (1)
Um presentation (1)Um presentation (1)
Um presentation (1)
 
Chap02
Chap02Chap02
Chap02
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
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
 

Similar to L14 exception handling

Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
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
rohitgudasi18
 

Similar to L14 exception handling (20)

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
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling 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 .
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 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 development
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 

More from teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
enums
enumsenums
enums
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

L14 exception handling

  • 1. Programming in Java Lecture 14: Exception Handling
  • 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.
  • 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); } }
  • 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.
  • 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.
  • 7. Throwable Exception Error Run-time Exception - VirtualMachine • IOEXception - ArithmeticException - NoSuchMethod • SQLException - ArrayIndexOutOf - StackOverFlow BoundsException - NullPointerException 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.
  • 9. Commonly used sub-classes of Exception • ArithmeticException • ArrayIndexOutOfBoundsException • NumberFormatException • NullPointerException • IOException
  • 10. Commonly used sub-classes of Errors • VirualMachineError • StackOverFlowError • NoClassDefFoundError • NoSuchMethodError
  • 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.
  • 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)
  • 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
  • 15. Keywords for Exception Handling • try • catch • throw • throws • finally
  • 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.
  • 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.
  • 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”);} } }
  • 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!"); } }}
  • 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.
  • 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); } } }
  • 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.
  • 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); } } }
  • 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.
  • 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'); } }
  • 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.
  • 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.
  • 28. Chained Exceptions • Throwing an exception along with another exception forms a chained exception.
  • 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"); } }
  • 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.
  • 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.
  • 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); } } }