SlideShare a Scribd company logo
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
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
AsisKumarTripathy
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Java unit3
Java unit3Java unit3
Java unit3
Abhishek Khune
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
Manav Prasad
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
Rajkattamuri
 
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
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
Nalinee Choudhary
 
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
Kuntal Bhowmick
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
dhrubo kayal
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
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
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 

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

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

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

BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
mamamaam477
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 

Recently uploaded (20)

BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 

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.