SlideShare a Scribd company logo
1 of 41
Download to read offline
Lecture 9
Error handling
Exceptions
Error handling
▪ If something goes wrong in our program, it is better to do
something with the error, rather than have the whole program
crash. This is to improve robustness.
▪ An exception is a runtime error that occurs during the normal
course of program execution.
▪ When an exception occurs, we say that the exception has been
thrown.
Error handling
▪ We can write code that catches a thrown exception i.e. runs
whenever the exception is thrown.
▪ If we don’t write code to handle the exceptions, there is a
default handler, but this will usually end the program or give
erroneous results.
▪ There is a lot more to this topic that we won’t cover.
Error handling
▪ InputMismatchException - Common exception you would
have seen already – mismatch between the data you
enter and what scanner input function you are using:
▪ Example: read two numbers in from console.
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scan.nextInt();
System.out.print("Enter second number: ");
int num2 = scan.nextInt();
System.out.print("Their sum: " + (num1 + num2));
Error handling
▪ What happens if the user enters a character? What will
nextInt() do?
▪ We get an error message – this particular exception is
InputMismatchException.
▪ We can handle exceptions using a try‐catch statement.
Try‐catch statements
Error handling
▪ if-statements, switch‐statements, loops etc all
determine the program flow – i.e. which line is executed
next.
▪ try-catch statements are similar in this way
try {
. . .
}
catch (. . .) {
. . .
}
Error handling
▪ If there are any exceptions that occur inside the try
section, then it stops executing the try block, but
instead runs the catch block.
▪ The type of exception that is caught is inside the
brackets of the catch statement.
try {
. . .
}
catch (. . .) {
. . .
}
Error handling
▪ If the user does enter an integer, this causes a
InputMismatchException and the println message is shown.
▪ Then the code after the catch block is run.
▪ If there is no exception, then the catch block isn’t run at all.
System.out.print("Enter first number: ");
try {
num1 = scan.nextInt();
}
catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
}
Error handling
▪ How can we exploit the fact that we leave the try block as
soon as there is an exception?
▪ We can put our try-catch block inside a loop and only change
the loop condition once we have finished the try-block.
Error handling
boolean done = false;
do {
System.out.print("Enter first number: ");
try {
num1 = scan.nextInt();
done = true;
}
catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
scan.next();
}
}while(!done);
Error handling
▪ We loop as long as done == false. done is only set to true,
once we finish the try-block.
▪ Notice, we added the scan.next() to the catch – this is to clear
out the exception causing input the user has entered.
▪ If we don’t, then scan.nextInt() will keep reading the same
non-integer and we will be stuck in a loop.
Exception classes
Error handling
Exception classes:
▪ Exception objects are instances of the Throwable class or one
of its subclasses.
Error handling
Error handling
Exception classes:
▪ Exception objects are instances of the Throwable class or one
of its subclasses.
▪ e.g. InputMismatchException class is a subclass of Throwable
class.
▪ Throwable class has two subclasses, Error and Exception.
– Error is for more serious issues
– Exception is for errors that can be handled – our focus.
Error handling
Exception classes:
▪ Throwable objects have methods that help us get information
about the exception.
▪ With catch (InputMismatchException e) we can then access
the methods of e: getMessage() and printStackTrace().
Error handling
Exception classes:
▪ Not all Throwable objects set their error messages, so
getMessage() will return null. You can also print the object
itself to get the type of error.
▪ printStackTrace() – this will show the sequence of method
calls from main to the exception – later.
Error handling
Different Exceptions
▪ RuntimeException:
– Superclass of exceptions that are thrown during normal operation
– Unchecked exception – program will compile if a try-catch block isn’t used.
– Subclass of Exception
▪ ArithmeticException:
– e.g. division by zero
– Subclass of RuntimeException
▪ NullPointerException:
– e.g. treating a null as if it were
an object
– Subclass of RuntimeException
Error handling
Different Exceptions
▪ IllegalArgumentException:
– e.g. method has been passed incorrect argument
– Subclass of RuntimeException
▪ NumberFormatException:
– e.g. converting string to
number but string doesn’t
have correct format
– Subclass of
IllegalArgumentException
Error handling
Different Exceptions
▪ IOException:
– e.g. some issue with I/O
– Checked exception – will cause a compile time error if it is not
handled.
– Subclass of Exception
▪ FileNotFoundException:
– e.g. file handling with file that
doesn’t exist.
– Subclass of IOException
Multiple catch blocks
Error handling
Multiple catch blocks
▪ We might want to catch different types of exceptions and
handle each one differently.
▪ Each catch‐block is checked in sequence for a match (of the
type of the Throwable object)
Error handling
▪ catch-blocks follow the try-blocks
try {
...
}
catch (Exception e) {
...
}
catch(InputMismatchException e) {
...
}
InputMismatchException
happens here
×
Error handling
Multiple catch blocks
▪ If Exception is checked first,
then every exception will match
with this one first and skip the
rest.
▪ The more specific Exception
classes (subclasses) should be
checked before the more
general Exception classes
(superclasses) otherwise, all the
exceptions will be caught by the
general Exception class
Error handling
Multiple catch blocks
▪ Check IllegalArgumentException
before RuntimeException before
Exception
Error handling
▪ So instead, we need to check the InputMismatchException
catch block first, and then Exception catch block
try {
...
}
catch (Exception e) {
...
}
catch(InputMismatchException e) {
...
}
InputMismatchException
happens here
try {
...
}
catch (InputMismatchException e) {
...
}
catch(Exception e) {
...
}
InputMismatchException
happens here
×

Error handling
▪ We can add a finally block as well – finally block is
always run.
▪ Even if there is a return statement – finally block
code is run first. try {
...
}
catch(Exception e) {
...
}
finally {
...
}
Throwing exceptions
Error handling
Throwing exceptions
▪ So far, the exception is thrown automatically. We can define
and throw our own exceptions.
▪ Example: we want the user to enter only positive numbers
– We instantiate an Exception object (or any subclass of the Throwable
class)
– Argument to the constructor is the message that is returned by
getMessage()
– We throw this object – keyword throw
if (num1 <= 0) {
throw new Exception("Number needs to be positive.");
}
Error handling
Throwing exceptions
▪ Now that we have thrown an exception, we need to catch it.
▪ Add another catch-block.
Error handling
try {
num1 = scan.nextInt();
if (num1 <= 0) {
throw new Exception("Number needs to be positive.");
}
done = true;
}
catch (InputMismatchException e) {
...
}
catch(Exception e) {
System.out.println(e.getMessage());
}
Exception Propagation
Error handling
Stack of method calls
▪ Recall that methods can call each other.
▪ Once a method has completed it returns to the method and
line that called it.
void A() {
//...
B();
//...
}
void B() {
//...
C();
//...
}
void C() {
//...
D();
//...
}
void D() {
//...
}
Error handling
▪ Instead of handling the exception ourselves – we can pass
it back down the stack of method calls, looking for a
matching catch-block.
▪ This is known as exception propagation
▪ Example from “Introduction to Object-Orientated
Programming with Java” (5th ed) by Wu
Error handling
Error handling
▪ If a method wants to propagate an exception, then it
must include the keyword throws.
▪ If we throw our own exceptions, then we either need to
catch them ourselves, or propagate it back down the
stack.
public void myMethod() throws Exception{...}
Assertions
Error handling
▪ Similar to throwing exceptions, we can assert that a
condition be true.
▪ If the condition is not true, it will throw an
AssertionError.
▪ Also need to enable assertions:
– Need to pass “–ea” as an argument to your program
– In Eclipse: Run  Run Configurations  <ProgramName> 
Arguments  VM Arguments  add “–ea”
Error handling
▪ Example the logic of our program has meant that x > y
▪ We can ensure this is the case using assertions:
try {
assert (x > y);
}
catch(AssertionError e) {
System.out.println(“Warning: x is not greater than y!");
}
If this condition is false, then it
will throw an AssertionError,
which can then be handled or not.

More Related Content

Similar to Lecture 9.pdf

Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
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 Lecture 9.pdf (20)

Exception handling
Exception handlingException handling
Exception handling
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java unit3
Java unit3Java unit3
Java unit3
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in 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 .
 
Nalinee java
Nalinee javaNalinee java
Nalinee 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
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
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
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 

More from SakhilejasonMsibi (11)

Lecture 6.pdf
Lecture 6.pdfLecture 6.pdf
Lecture 6.pdf
 
Lecture 4 part 2.pdf
Lecture 4 part 2.pdfLecture 4 part 2.pdf
Lecture 4 part 2.pdf
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Lecture2.pdf
Lecture2.pdfLecture2.pdf
Lecture2.pdf
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
 
Lecture 7.pdf
Lecture 7.pdfLecture 7.pdf
Lecture 7.pdf
 
Lecture 5.pdf
Lecture 5.pdfLecture 5.pdf
Lecture 5.pdf
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Lecture 4 part 1.pdf
Lecture 4 part 1.pdfLecture 4 part 1.pdf
Lecture 4 part 1.pdf
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
 

Recently uploaded

Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 

Recently uploaded (20)

Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
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
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
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
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 

Lecture 9.pdf

  • 3. Error handling ▪ If something goes wrong in our program, it is better to do something with the error, rather than have the whole program crash. This is to improve robustness. ▪ An exception is a runtime error that occurs during the normal course of program execution. ▪ When an exception occurs, we say that the exception has been thrown.
  • 4. Error handling ▪ We can write code that catches a thrown exception i.e. runs whenever the exception is thrown. ▪ If we don’t write code to handle the exceptions, there is a default handler, but this will usually end the program or give erroneous results. ▪ There is a lot more to this topic that we won’t cover.
  • 5. Error handling ▪ InputMismatchException - Common exception you would have seen already – mismatch between the data you enter and what scanner input function you are using: ▪ Example: read two numbers in from console. Scanner scan = new Scanner(System.in); System.out.print("Enter first number: "); int num1 = scan.nextInt(); System.out.print("Enter second number: "); int num2 = scan.nextInt(); System.out.print("Their sum: " + (num1 + num2));
  • 6. Error handling ▪ What happens if the user enters a character? What will nextInt() do? ▪ We get an error message – this particular exception is InputMismatchException. ▪ We can handle exceptions using a try‐catch statement.
  • 8. Error handling ▪ if-statements, switch‐statements, loops etc all determine the program flow – i.e. which line is executed next. ▪ try-catch statements are similar in this way try { . . . } catch (. . .) { . . . }
  • 9. Error handling ▪ If there are any exceptions that occur inside the try section, then it stops executing the try block, but instead runs the catch block. ▪ The type of exception that is caught is inside the brackets of the catch statement. try { . . . } catch (. . .) { . . . }
  • 10. Error handling ▪ If the user does enter an integer, this causes a InputMismatchException and the println message is shown. ▪ Then the code after the catch block is run. ▪ If there is no exception, then the catch block isn’t run at all. System.out.print("Enter first number: "); try { num1 = scan.nextInt(); } catch (InputMismatchException e) { System.out.println("Please enter an integer."); }
  • 11. Error handling ▪ How can we exploit the fact that we leave the try block as soon as there is an exception? ▪ We can put our try-catch block inside a loop and only change the loop condition once we have finished the try-block.
  • 12. Error handling boolean done = false; do { System.out.print("Enter first number: "); try { num1 = scan.nextInt(); done = true; } catch (InputMismatchException e) { System.out.println("Please enter an integer."); scan.next(); } }while(!done);
  • 13. Error handling ▪ We loop as long as done == false. done is only set to true, once we finish the try-block. ▪ Notice, we added the scan.next() to the catch – this is to clear out the exception causing input the user has entered. ▪ If we don’t, then scan.nextInt() will keep reading the same non-integer and we will be stuck in a loop.
  • 15. Error handling Exception classes: ▪ Exception objects are instances of the Throwable class or one of its subclasses.
  • 17. Error handling Exception classes: ▪ Exception objects are instances of the Throwable class or one of its subclasses. ▪ e.g. InputMismatchException class is a subclass of Throwable class. ▪ Throwable class has two subclasses, Error and Exception. – Error is for more serious issues – Exception is for errors that can be handled – our focus.
  • 18. Error handling Exception classes: ▪ Throwable objects have methods that help us get information about the exception. ▪ With catch (InputMismatchException e) we can then access the methods of e: getMessage() and printStackTrace().
  • 19. Error handling Exception classes: ▪ Not all Throwable objects set their error messages, so getMessage() will return null. You can also print the object itself to get the type of error. ▪ printStackTrace() – this will show the sequence of method calls from main to the exception – later.
  • 20. Error handling Different Exceptions ▪ RuntimeException: – Superclass of exceptions that are thrown during normal operation – Unchecked exception – program will compile if a try-catch block isn’t used. – Subclass of Exception ▪ ArithmeticException: – e.g. division by zero – Subclass of RuntimeException ▪ NullPointerException: – e.g. treating a null as if it were an object – Subclass of RuntimeException
  • 21. Error handling Different Exceptions ▪ IllegalArgumentException: – e.g. method has been passed incorrect argument – Subclass of RuntimeException ▪ NumberFormatException: – e.g. converting string to number but string doesn’t have correct format – Subclass of IllegalArgumentException
  • 22. Error handling Different Exceptions ▪ IOException: – e.g. some issue with I/O – Checked exception – will cause a compile time error if it is not handled. – Subclass of Exception ▪ FileNotFoundException: – e.g. file handling with file that doesn’t exist. – Subclass of IOException
  • 24. Error handling Multiple catch blocks ▪ We might want to catch different types of exceptions and handle each one differently. ▪ Each catch‐block is checked in sequence for a match (of the type of the Throwable object)
  • 25. Error handling ▪ catch-blocks follow the try-blocks try { ... } catch (Exception e) { ... } catch(InputMismatchException e) { ... } InputMismatchException happens here ×
  • 26. Error handling Multiple catch blocks ▪ If Exception is checked first, then every exception will match with this one first and skip the rest. ▪ The more specific Exception classes (subclasses) should be checked before the more general Exception classes (superclasses) otherwise, all the exceptions will be caught by the general Exception class
  • 27. Error handling Multiple catch blocks ▪ Check IllegalArgumentException before RuntimeException before Exception
  • 28. Error handling ▪ So instead, we need to check the InputMismatchException catch block first, and then Exception catch block try { ... } catch (Exception e) { ... } catch(InputMismatchException e) { ... } InputMismatchException happens here try { ... } catch (InputMismatchException e) { ... } catch(Exception e) { ... } InputMismatchException happens here × 
  • 29. Error handling ▪ We can add a finally block as well – finally block is always run. ▪ Even if there is a return statement – finally block code is run first. try { ... } catch(Exception e) { ... } finally { ... }
  • 31. Error handling Throwing exceptions ▪ So far, the exception is thrown automatically. We can define and throw our own exceptions. ▪ Example: we want the user to enter only positive numbers – We instantiate an Exception object (or any subclass of the Throwable class) – Argument to the constructor is the message that is returned by getMessage() – We throw this object – keyword throw if (num1 <= 0) { throw new Exception("Number needs to be positive."); }
  • 32. Error handling Throwing exceptions ▪ Now that we have thrown an exception, we need to catch it. ▪ Add another catch-block.
  • 33. Error handling try { num1 = scan.nextInt(); if (num1 <= 0) { throw new Exception("Number needs to be positive."); } done = true; } catch (InputMismatchException e) { ... } catch(Exception e) { System.out.println(e.getMessage()); }
  • 35. Error handling Stack of method calls ▪ Recall that methods can call each other. ▪ Once a method has completed it returns to the method and line that called it. void A() { //... B(); //... } void B() { //... C(); //... } void C() { //... D(); //... } void D() { //... }
  • 36. Error handling ▪ Instead of handling the exception ourselves – we can pass it back down the stack of method calls, looking for a matching catch-block. ▪ This is known as exception propagation ▪ Example from “Introduction to Object-Orientated Programming with Java” (5th ed) by Wu
  • 38. Error handling ▪ If a method wants to propagate an exception, then it must include the keyword throws. ▪ If we throw our own exceptions, then we either need to catch them ourselves, or propagate it back down the stack. public void myMethod() throws Exception{...}
  • 40. Error handling ▪ Similar to throwing exceptions, we can assert that a condition be true. ▪ If the condition is not true, it will throw an AssertionError. ▪ Also need to enable assertions: – Need to pass “–ea” as an argument to your program – In Eclipse: Run  Run Configurations  <ProgramName>  Arguments  VM Arguments  add “–ea”
  • 41. Error handling ▪ Example the logic of our program has meant that x > y ▪ We can ensure this is the case using assertions: try { assert (x > y); } catch(AssertionError e) { System.out.println(“Warning: x is not greater than y!"); } If this condition is false, then it will throw an AssertionError, which can then be handled or not.