SlideShare a Scribd company logo
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 (20)

PDF
Exception Handling in Java
Java2Blog
 
PPTX
Java exception handling
Md. Tanvir Hossain
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPT
Java exception
Arati Gadgil
 
PPTX
Exception handling in java
ARAFAT ISLAM
 
PPTX
Multithreading in java
Raghu nath
 
PPSX
Exception Handling
Reddhi Basu
 
PPT
Exception handling
M Vishnuvardhan Reddy
 
PPTX
Control statements in java
Madishetty Prathibha
 
PPTX
Exception handling in java
Lovely Professional University
 
PPTX
Exception handling in java
Elizabeth alexander
 
PDF
Java - Exception Handling Concepts
Victer Paul
 
PPTX
Exception Handling in Java
lalithambiga kamaraj
 
PDF
Java exception handling ppt
JavabynataraJ
 
PPTX
Methods in java
chauhankapil
 
PPTX
Exception handling
PhD Research Scholar
 
PPTX
Java Method, Static Block
Infoviaan Technologies
 
PPTX
Java Lambda Expressions.pptx
SameerAhmed593310
 
PPTX
Interface in java
PhD Research Scholar
 
PDF
Java Thread Synchronization
Benj Del Mundo
 
Exception Handling in Java
Java2Blog
 
Java exception handling
Md. Tanvir Hossain
 
Exception Handling in JAVA
SURIT DATTA
 
Java exception
Arati Gadgil
 
Exception handling in java
ARAFAT ISLAM
 
Multithreading in java
Raghu nath
 
Exception Handling
Reddhi Basu
 
Exception handling
M Vishnuvardhan Reddy
 
Control statements in java
Madishetty Prathibha
 
Exception handling in java
Lovely Professional University
 
Exception handling in java
Elizabeth alexander
 
Java - Exception Handling Concepts
Victer Paul
 
Exception Handling in Java
lalithambiga kamaraj
 
Java exception handling ppt
JavabynataraJ
 
Methods in java
chauhankapil
 
Exception handling
PhD Research Scholar
 
Java Method, Static Block
Infoviaan Technologies
 
Java Lambda Expressions.pptx
SameerAhmed593310
 
Interface in java
PhD Research Scholar
 
Java Thread Synchronization
Benj Del Mundo
 

Viewers also liked (9)

PDF
Java: Exception Handling
Kan-Han (John) Lu
 
PPT
Um presentation (1)
Ethel Joy Sumaljag
 
PPT
Chap02
Jotham Gadot
 
PPTX
Exception handling in java
Adil Mehmoood
 
DOCX
Java Exception handling
Garuda Trainings
 
PPT
Exception Handling Java
ankitgarg_er
 
PPT
Exception handling in java
Pratik Soares
 
PPTX
Exception handling in Java
Abhishek Pachisia
 
ODP
Exception Handling In Java
parag
 
Java: Exception Handling
Kan-Han (John) Lu
 
Um presentation (1)
Ethel Joy Sumaljag
 
Chap02
Jotham Gadot
 
Exception handling in java
Adil Mehmoood
 
Java Exception handling
Garuda Trainings
 
Exception Handling Java
ankitgarg_er
 
Exception handling in java
Pratik Soares
 
Exception handling in Java
Abhishek Pachisia
 
Exception Handling In Java
parag
 
Ad

Similar to L14 exception handling (20)

PPT
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
Luis Goldster
 
PPT
Exception
Hoang Nguyen
 
PPT
Exception
Young Alista
 
PPT
Exception
James Wong
 
PPT
Exception
Harry Potter
 
PPTX
Java exception handling
GaneshKumarKanthiah
 
PPT
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
PPT
8.Exception handling latest(MB).ppt .
happycocoman
 
PPTX
Pi j4.2 software-reliability
mcollison
 
PPTX
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
PPTX
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
PPTX
Java-Unit 3- Chap2 exception handling
raksharao
 
PPTX
Chap2 exception handling
raksharao
 
PPTX
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
PPTX
Exception handling in java
yugandhar vadlamudi
 
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Exception
Tony Nguyen
 
Exception
Tony Nguyen
 
Exception
Fraboni Ec
 
Exception
Fraboni Ec
 
Exception
Luis Goldster
 
Exception
Hoang Nguyen
 
Exception
Young Alista
 
Exception
James Wong
 
Exception
Harry Potter
 
Java exception handling
GaneshKumarKanthiah
 
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
8.Exception handling latest(MB).ppt .
happycocoman
 
Pi j4.2 software-reliability
mcollison
 
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Java-Unit 3- Chap2 exception handling
raksharao
 
Chap2 exception handling
raksharao
 
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Exception handling in java
yugandhar vadlamudi
 
Ad

More from teach4uin (20)

PPTX
Controls
teach4uin
 
PPT
validation
teach4uin
 
PPT
validation
teach4uin
 
PPT
Master pages
teach4uin
 
PPTX
.Net framework
teach4uin
 
PPT
Scripting languages
teach4uin
 
PPTX
Css1
teach4uin
 
PPTX
Code model
teach4uin
 
PPT
Asp db
teach4uin
 
PPTX
State management
teach4uin
 
PPT
security configuration
teach4uin
 
PPT
static dynamic html tags
teach4uin
 
PPT
static dynamic html tags
teach4uin
 
PPTX
New microsoft office power point presentation
teach4uin
 
PPT
.Net overview
teach4uin
 
PPT
Stdlib functions lesson
teach4uin
 
PPT
enums
teach4uin
 
PPT
memory
teach4uin
 
PPT
array
teach4uin
 
PPT
storage clas
teach4uin
 
Controls
teach4uin
 
validation
teach4uin
 
validation
teach4uin
 
Master pages
teach4uin
 
.Net framework
teach4uin
 
Scripting languages
teach4uin
 
Css1
teach4uin
 
Code model
teach4uin
 
Asp db
teach4uin
 
State management
teach4uin
 
security configuration
teach4uin
 
static dynamic html tags
teach4uin
 
static dynamic html tags
teach4uin
 
New microsoft office power point presentation
teach4uin
 
.Net overview
teach4uin
 
Stdlib functions lesson
teach4uin
 
enums
teach4uin
 
memory
teach4uin
 
array
teach4uin
 
storage clas
teach4uin
 

Recently uploaded (20)

PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
July Patch Tuesday
Ivanti
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
July Patch Tuesday
Ivanti
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 

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); } } }