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 Z blue exception

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
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 Z blue exception (20)

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
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
 
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

1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxNadaHaitham1
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEselvakumar948
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 

Recently uploaded (20)

1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 

Z blue exception

  • 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