Handling Exceptions.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Checked/Uncheck Exception And finally Block. Catching Any Exception It is possible to create a handler that catches any kind of exception. (This is possible.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
JSP Exception Handling 20-Oct-15. JSP - E XCEPTION H ANDLING When you are writing JSP code, a programmer may leave a coding errors which can occur at.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Object Throwable ErrorException RuntimeException.
Java Exceptions a quick review….
Generics, Exceptions and Undo Command
Exceptions In this lecture:
Exceptions: When things go wrong
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Introduction to OO Program Design
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Exception Handling in Java
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Java Exceptions Dan Fleck CS211.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 25-Apr-19.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Handling Exceptions

Why Exceptions? Programmers tend to think they are invincible, which is ABSOLUTELY wrong. Recall we are humans. The ideal time to catch the error is at compile time. However, the real nasty errors occur during runtime. For programmers to handle runtime errors, Java provides so called exception handling. Underlying idea of exception handling in Java is: badly-formed code should not be run Instead of executing erroneous code, let the user know.

Exceptional Condition An exceptional condition or situation is what prevents the continuation of program. It can be anything. User Input Error Device Error Physical Limitation Code Errors --- This is where most exceptions are thrown.

Throwing Exception A Java method can throw an Exception if it is facing bad situation it can not handle. Notice it is programmer who decide which exception to throw. Throws means returns an Exception to its caller. Exception is a class, which means we should create an instance of it using new keyword. if ( t == null ) throws new NullPointerException(); A method which may throw an exception should let compiler know its chance of throwing an exception. public string readLine() throws IOException

Exception Hierarchy Throwable Error Exception IOException RuntimeException MalformedURLException NullPointerException

RumtimeException A RuntimeException occurs because of programming error, which may include: A bad cast (ClassCastException) An out-of-bound array access (ArrayIndexOutOfBoundsException) A null pointer access (NullPointerException) If you encounters a RuntimeException, It is completely your fault!!!. Generally, program will be terminated when a RuntimeException occurs. However, it leaves lots of useful information for debugging.

Advantages of Exception Handling In C, we need to check return values of every function call for error handling. if ( read(buf,SIZE) == -1 ) This kind of error handling is very tedious, although necessary. In Java, we can designate separate exception handling region. You try to run a block of code, which may throw Exceptions. You catch the thrown exception in a designated area. This makes reading, writing, and debugging code becomes much clearer.

Context Every Java statement belongs to a context of certain level. You can think the current context as the current scope. Or every {,} pair constitutes a context. A try/catch block forms a context since it is enclosed by a pair of {,}. Every called method forms a lower context and calling method forms higher context. void a() int b() { { int y = b(); return 3; } }

Context cont. Every method is returned by executing return keyword, which may physically return some value or not. Here, return means returning to the higher context. All these calling and returning sequences are processed via stack. Since stack is so important in many ways, it is covered briefly here.

Exception Handling At the point where the runtime error occurs, you probably do not know what to do. Only thing you do know is that the code should not continue on. Then, whose job is it to figure out what to do? Let’s consider this from the context point of view. try { URL url = new URL(“http://www.eecs.edu”); }catch (MalformedURLException e) { // Handling should be here, where is the higher context. } URL() constructor does not know what to do when there is something wrong with input string. It is the higher context that should handle exception.

Catching any exception It is possible to create a handler that catches any kind of exception. (This is possible due to the class hierarchy) Treat every possible exception as Exception, which is the base class that’s what programmers are most interested in. Three useful methods in Exception class. String getMessage() Gets the detailed message String toString() Overridden method from Object void printStackTrace() Prints out calling sequence in reverse order.

public class ExceptionDemo { try { thrower(); } catch (Exception e) { System.out.println(“I got it!!!”); System.out.println(“message: “ + e.getMessage()); System.out.println(“more message: “ + e.toString()); e.printStackTrace(); } private void thrower() throws IOException { throw new Exception(“This is harmless exception”); public static void main(String args[]) { new ExceptionDemo();

Output Result I got it!!! message: This is harmless exception more message: java.io.IOException: This is harmless exception java.io.IOException: This is harmless exception at ExceptionDemo.thrower(ExceptionDemo.java:17) at ExceptionDemo.<init>(ExceptionDemo.java:6) at ExceptionDemo.main(ExceptionDemo.java:21)

public class Runtime { Runtime() { thrower(); System.out.println("I will never reach here!"); } private void thrower() { throw new ArrayIndexOutOfBoundsException(); public static void main(String args[]) { new Runtime2();

Output Result Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Runtime2.thrower(Runtime2.java:10) at Runtime2.<init>(Runtime2.java:5) at Runtime2.main(Runtime2.java:14)

public class Runtime { Runtime() { try { thrower(); }catch (Exception e) { System.out.println("I got it!!!"); System.out.println("message: " + e.getMessage()); System.out.println("more message: " + e.toString()); e.printStackTrace(); } System.out.println(”I finally got here!!!"); private void thrower() { throw new ArrayIndexOutOfBoundsException(“This is a fake exception); public static void main(String args[]) { new Runtime();

Output Result I got it!!! message: This is a fake exception more message: java.lang.ArrayIndexOutOfBoundsException: This is a fake exception java.lang.ArrayIndexOutOfBoundsException: This is a fake exception at Runtime.thrower(Runtime.java:15) at Runtime.<init>(Runtime.java:4) at Runtime.main(Runtime.java:19) I finally got here!!!