SlideShare a Scribd company logo
1 of 15
CHAPTER FIVE
EXCEPTIONS
HANDLING ERRORS WITH EXCEPTIONS
Exception Handling
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
What happens when this method is used to take the average of an array of length zero?
Program throws an exception and fails.
java.lang.ArithmeticException: / by zero
Exception Handling
What is an Exception?
An error event that disrupts the program flow and may cause a program to fail.
Some examples:
Performing illegal arithmetic
Illegal arguments to methods
Accessing an out-of-bounds array element
Hardware failures
Writing to a read-only file
"An exception was thrown" is the proper java terminology for "an error
happened."
public class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}}
Output:
Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Handling
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
• What exception class?
• Which array index is out of bounds?
• What method throws the exception?
• What file contains the method?
• What line of the file throws the exception?
ArrayIndexOutOfBoundsException
2
main
ExceptionExample.java
4
Exception Handling
• A java exception is an object that describes an exceptional (that is ‘error’) condition that has
occurred in a piece of code at runtime.
• When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.
• That method may handle the exception itself, or pass it on.
• Java exception handling is managed by 5 keywords: try, catch, throw, throws and finally.
Exception Error
Throwable
Runtime Exception
Exception Handling
Exception class is used for exceptional conditions that user programs should catch.
Exception of type runtimeexception are automatically defined for the programs that you write.
Error class defines exceptions that are not expected to be caught under normal
circumstances.
Uncaught Exceptions
When java runtime system detects an exception
It throws this exception.
Once thrown it must be caught by an exception handler and dealt with immediately.
If exception handling code is not written in the program , default handler of java catch the
exception.
The default handler displays a string describing the exception & terminates the program.
 Handling exceptions by ourselves provides 2 benefits.
• First it allows you to fix the error.
• Second it prevents the program from automatically terminating.
Exception Handling
Use a try-catch block to handle exceptions that are thrown
try {
// code that might throw exception
} catch ([type of Exception] e) { // what to do if exception is thrown }
class Example{
public static void main(String args[])
int d,a;
try
{
d=0;
a=42/d;
}catch (ArithmeticException e) { System.out.println(“Division by zero."); }
}
Exception Handling
Once an exception is thrown program control transfers to the try block from a catch.
Once the catch statement has executed, program control continues with the next line in the
program following the entire try/catch mechanism.
Example
public int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
public void printAverage(int[] a) {
try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
}
}
Exception Handling
A try and its catch statement form a unit.
You cannot use try on a single statement.
The goal of most well-constructed catch clause should be to resolve the exceptional condition and then
continue on as if the error had never happened.
Handle multiple possible exceptions by multiple successive catch blocks
try {
// code that might throw multiple exception
}catch (IOException e) {
// handle IOException and all subclasses
}catch (ClassNotFoundException e2) {
// handle ClassNotFoundException }
When an exception is thrown, each catch statement is inspected in order and the first one
whose type matches that of the exception is executed. After one catch statement executes,
the others are by passed, and execution continues after the try/catch block.
Exception Handling
Exceptions Terminology
When an exception happens we say it was thrown or raised
When an exception is dealt with, we say the exception is was handled or caught
Unchecked Exceptions
All the exceptions we've seen so far have been unchecked exceptions, or runtime exceptions
Usually occur because of programming errors, when code is not robust enough to prevent them
They are numerous and can be ignored by the programmer
Common Unchecked Exceptions
NullPointerException reference is null and should not be
IllegalArgumentException method argument is improper is some way
Checked Exceptions
Usually occur because of errors programmer cannot control:
Examples: hardware failures, unreadable files
They are less frequent and they cannot be ignored by the programmer . . .
Exception Class Hierarchy
Unchecked Exceptions Checked Exceptions
Exception Handling
Dealing with Checked Exceptions
• Every method must catch (handle) checked exceptions or specify that it may throw them
• Specify with the throws keyword
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch (FileNotFoundException e) {
System.out.println("file was not found");
}
}
OR
void readFile(String filename) throws FileNotFoundException {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
Exception Handling
The Throws Clause
When you write a method that can throw exceptions to its caller, it is useful to document that fact for
other programmers who use your code.
This provides them with the opportunity to deal with those exceptions.
And also it will let you know which exceptions can be thrown from code written by others.
We do this by including a throws clause in the method’s declaration.
A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions except error or RunTimeException.
Throwing Exceptions Example
public static int average(int[] a) {
if (a.length == 0) {
throw new IllegalArgumentException("array is empty");
}
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
Checked and Unchecked Exceptions
Checked Exception Unchecked Exception
 Not subclass of
RuntimeException
 Subclass of RuntimeException
 If not caught, method must
specify it to be thrown
 If not caught, method may
specify it to be thrown
 For errors that the programmer
cannot directly prevent from
occurring
 For errors that the programmer
can directly prevent from
occurring,
 IOException,
FileNotFoundException,
SocketException
 NullPointerException,
IllegalArgumentException,
IllegalStateException
Keyword Summary
Four New Java Keywords
Try and catch – used to handle exceptions that may be
thrown
Throws – to specify which exceptions a method throws in
method declaration
Throw – to throw an exception

More Related Content

What's hot

What's hot (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
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 in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception
Java exception Java exception
Java exception
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handling Exception handling
Exception handling
 
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 in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 

Similar to Learn how to handle errors with Java exceptions

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
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
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
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
 

Similar to Learn how to handle errors with Java exceptions (20)

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
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
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Exception handling
Exception handlingException handling
Exception handling
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling
Exception handlingException handling
Exception handling
 

More from Narayana Swamy

AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINESAICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINESNarayana Swamy
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)Narayana Swamy
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)Narayana Swamy
 
Oop inheritance chapter 3
Oop inheritance chapter 3Oop inheritance chapter 3
Oop inheritance chapter 3Narayana Swamy
 

More from Narayana Swamy (7)

AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINESAICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINES
 
Files io
Files ioFiles io
Files io
 
Exceptions
ExceptionsExceptions
Exceptions
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
 
Oop inheritance chapter 3
Oop inheritance chapter 3Oop inheritance chapter 3
Oop inheritance chapter 3
 
Exceptions
ExceptionsExceptions
Exceptions
 

Recently uploaded

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 

Recently uploaded (20)

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 

Learn how to handle errors with Java exceptions

  • 2. Exception Handling public static int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; } What happens when this method is used to take the average of an array of length zero? Program throws an exception and fails. java.lang.ArithmeticException: / by zero
  • 3. Exception Handling What is an Exception? An error event that disrupts the program flow and may cause a program to fail. Some examples: Performing illegal arithmetic Illegal arguments to methods Accessing an out-of-bounds array element Hardware failures Writing to a read-only file "An exception was thrown" is the proper java terminology for "an error happened." public class ExceptionExample { public static void main(String args[]) { String[] greek = {"Alpha", "Beta"}; System.out.println(greek[2]); }} Output: Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)
  • 4. Exception Handling Exception Message Details Exception message format: [exception class]: [additional description of exception] at [class].[method]([file]:[line number]) Example: java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4) • What exception class? • Which array index is out of bounds? • What method throws the exception? • What file contains the method? • What line of the file throws the exception? ArrayIndexOutOfBoundsException 2 main ExceptionExample.java 4
  • 5. Exception Handling • A java exception is an object that describes an exceptional (that is ‘error’) condition that has occurred in a piece of code at runtime. • When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. • That method may handle the exception itself, or pass it on. • Java exception handling is managed by 5 keywords: try, catch, throw, throws and finally. Exception Error Throwable Runtime Exception
  • 6. Exception Handling Exception class is used for exceptional conditions that user programs should catch. Exception of type runtimeexception are automatically defined for the programs that you write. Error class defines exceptions that are not expected to be caught under normal circumstances. Uncaught Exceptions When java runtime system detects an exception It throws this exception. Once thrown it must be caught by an exception handler and dealt with immediately. If exception handling code is not written in the program , default handler of java catch the exception. The default handler displays a string describing the exception & terminates the program.  Handling exceptions by ourselves provides 2 benefits. • First it allows you to fix the error. • Second it prevents the program from automatically terminating.
  • 7. Exception Handling Use a try-catch block to handle exceptions that are thrown try { // code that might throw exception } catch ([type of Exception] e) { // what to do if exception is thrown } class Example{ public static void main(String args[]) int d,a; try { d=0; a=42/d; }catch (ArithmeticException e) { System.out.println(“Division by zero."); } }
  • 8. Exception Handling Once an exception is thrown program control transfers to the try block from a catch. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism. Example public int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; } public void printAverage(int[] a) { try { int avg = average(a); System.out.println("the average is: " + avg); } catch (ArithmeticException e) { System.out.println("error calculating average"); } }
  • 9. Exception Handling A try and its catch statement form a unit. You cannot use try on a single statement. The goal of most well-constructed catch clause should be to resolve the exceptional condition and then continue on as if the error had never happened. Handle multiple possible exceptions by multiple successive catch blocks try { // code that might throw multiple exception }catch (IOException e) { // handle IOException and all subclasses }catch (ClassNotFoundException e2) { // handle ClassNotFoundException } When an exception is thrown, each catch statement is inspected in order and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are by passed, and execution continues after the try/catch block.
  • 10. Exception Handling Exceptions Terminology When an exception happens we say it was thrown or raised When an exception is dealt with, we say the exception is was handled or caught Unchecked Exceptions All the exceptions we've seen so far have been unchecked exceptions, or runtime exceptions Usually occur because of programming errors, when code is not robust enough to prevent them They are numerous and can be ignored by the programmer Common Unchecked Exceptions NullPointerException reference is null and should not be IllegalArgumentException method argument is improper is some way Checked Exceptions Usually occur because of errors programmer cannot control: Examples: hardware failures, unreadable files They are less frequent and they cannot be ignored by the programmer . . .
  • 11. Exception Class Hierarchy Unchecked Exceptions Checked Exceptions
  • 12. Exception Handling Dealing with Checked Exceptions • Every method must catch (handle) checked exceptions or specify that it may throw them • Specify with the throws keyword void readFile(String filename) { try { FileReader reader = new FileReader("myfile.txt"); // read from file . . . } catch (FileNotFoundException e) { System.out.println("file was not found"); } } OR void readFile(String filename) throws FileNotFoundException { FileReader reader = new FileReader("myfile.txt"); // read from file . . . }
  • 13. Exception Handling The Throws Clause When you write a method that can throw exceptions to its caller, it is useful to document that fact for other programmers who use your code. This provides them with the opportunity to deal with those exceptions. And also it will let you know which exceptions can be thrown from code written by others. We do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions except error or RunTimeException. Throwing Exceptions Example public static int average(int[] a) { if (a.length == 0) { throw new IllegalArgumentException("array is empty"); } int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; }
  • 14. Checked and Unchecked Exceptions Checked Exception Unchecked Exception  Not subclass of RuntimeException  Subclass of RuntimeException  If not caught, method must specify it to be thrown  If not caught, method may specify it to be thrown  For errors that the programmer cannot directly prevent from occurring  For errors that the programmer can directly prevent from occurring,  IOException, FileNotFoundException, SocketException  NullPointerException, IllegalArgumentException, IllegalStateException
  • 15. Keyword Summary Four New Java Keywords Try and catch – used to handle exceptions that may be thrown Throws – to specify which exceptions a method throws in method declaration Throw – to throw an exception