Copyright © 1999-2012 Curt Hill Error Handling in Java Throwing and catching exceptions.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Index Exception handling Exception In Java Exception Types
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
For use of Cleveland State's IST410 Students only 1 Exception.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
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.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
11-Jun-15 Exceptions. 2 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.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
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.
Java Programming: Guided Learning with Early Objects
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
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.
CS102 – Exceptions David Davenport Latest: May 2015
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Chapter 11—Exceptions Handling Exceptions Throwing Exceptions.
Exception Handling in Java
Exception Handling Chapter 9 Edited by JJ.
Throwing and catching exceptions
Chapter 12: Exceptions and Advanced File I/O
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions

Copyright © Curt Hill Exceptions Exception: An unexpected problem that prevents normal continuation of the algorithm Examples: divide by zero using a null handle Uncaught exceptions are generally run-time errors

Copyright © Curt Hill Traditional Exception Handling In many languages there is no error handling If we think there is a good chance that a divisor could be zero, we could test it: if(k==0) { // handle error … else j = m/k;

Copyright © Curt Hill Problems There are just too many possible ways to generate an exception If we tested each one with an if most of the code would be error testing

Copyright © Curt Hill Java Exception Handling Java exception handling is having one error handling routine that intercepts all divide by zero exceptions The exception handler can be a long ways from the exception

Copyright © Curt Hill Two Parts of Exception Handling Finding the error and announcing it as an error –Throwing an exception –This uses the throw and throws keyword Handling the exception –Recovery or error handling –This uses the try, catch, and finally keyword

Copyright © Curt Hill Exceptions Everything in Java is a class –Exception is no exception There are at least 35 subclasses of Exception including –ClassNotFoundException –GeneralSecurityException (21 subclasses) –IOException (21 subclasses) –RuntimeException (29 subclasses) Many of these are subclassed as well

Copyright © Curt Hill Exceptions Exception SQLException IOException SecurityException NullPointerException RunTimeException ArithmeticException IndexOutOfBoundsException FileNotFoundException EOFException AWTException ZipException

Copyright © Curt Hill Catching the exception Uses the try catch block try introduces a compound statement This is followed by one or more catch clauses There can also be one finally clause Each catch clause is like a one parameter method that handles that kind of exception

Copyright © Curt Hill try catch syntax Form is: try { // code... } catch (ExceptionType_1 e) { handle exception 1} catch (ExceptionType_2 e) { handle exception 2 }... finally { always executed }

Copyright © Curt Hill Form of catch catch (type parm){stmts} Parameter is an exception type Derived from Exception Only usable in the compound statement Compound statement is like a method body and the Exception (or subclass) is the only parameter

Copyright © Curt Hill Example try catch Catch divide by zero: try { fun(x); } catch(ArithmeticException a){ System.out.println(“Oops”); } catch(Exception e){ System.out.println(“Oops2”); } The error can be in the try or in any function called from within the try

Copyright © Curt Hill Exceptions and the throw Many exceptions are thrown automatically by the Java Virtual Machine These require no intervention on our part We can also throw them manually

Copyright © Curt Hill Throwing an Exception Use new to allocate the exception Use the throw keyword to launch it Example: if(j==0) throw new ArithmeticException(“j was zero”);

Copyright © Curt Hill Exception Constructors Exception and its subclasses usually have two constructors A default A constructor that takes a message This message can be extracted in the catch

Copyright © Curt Hill Exception Methods Exception and its subclasses have several methods of importance getMessage() –Returns the constructor message printStackTrace –No parameters: display on error file –One parameter: file to display on

Copyright © Curt Hill A Better try catch try {... } catch(ArithmeticException a){ System.out.println( a.getMessage()); printStackTrace(System.out); }

Copyright © Curt Hill Cause and Effect The throw and catch do not have to be near each other The throw is like a super return The current function is exited as well as any between this one and the function containing the try and catch Consider in next screen, a main function with a try catch that calls Fun_1, which calls Fun_2, which calls Oops, which throws an exception

Copyright © Curt Hill Call example try{ Fun_1(…) catch(…) throw Oops(...); Fun_2(…) main Fun_1 Fun_2 Oops

Copyright © Curt Hill Exception Processing The call stack between throw and catch is flushed The function and all those in between are terminated They may be re-executed later, but they can not be resumed

Copyright © Curt Hill Nested Trys We do not usually nest a try within another However, to get to our exception we may go through several try catch pairs in several methods The exception is always caught by the closest try Closest in terms of most recently called function

Copyright © Curt Hill Second call example try{ Fun_1(…) catch(…){…} throw Oops(...); try { Fun_2(…); catch(…){…} main Fun_1 Fun_2 Oops

Copyright © Curt Hill Throwing Revisited The throw keyword launches an exception Any function that contains any of these must either handle the exception or announce that it is a possibility The announcement is done with the throws clause

Copyright © Curt Hill The throws clause The throws clause mentions the exception thrown Follows the function parameter list Precedes the opening brace int f(...) throws Exception {... throw new Exception(“Oops”); Announces the possibility of this error, even though it might or might not actually occur

Copyright © Curt Hill More on throws If a function calls a function with a throws clause it must catch what is thrown or have a throws itself There always has to be a catch Throws is not needed for automatics thrown by JVM –Functions that throw a RunTimeException or its subclasses do not need a throws –This is only exception of JVM

Methods with Throws Many methods have throws –Particularly in regard to I/O A call of these methods must be within a try catch –Otherwise a syntax error is given Fortunately, that syntax error tells the programmer exactly what exception is to be thrown Copyright © Curt Hill

Multiple Catches A try catch statement can have many catch clauses They are tried in order from top to bottom What the clause handles is based on the parameter to the catch Put the specifics first and the generals later See the subclasses of Exception for more details

Copyright © Curt Hill Order Consider the following: try {…} catch(Exception e){…} catch(IOException i){…} The second catch can never be executed IOException is a subclass of Exception Since checking starts from top, there is no condition that could trigger the second that would not be caught by the first Java compiler flags as an error

Copyright © Curt Hill Finally Clause is always executed, whether exception occurs or not Provides for final cleanup –File closing or cleanup –Network connection termination It is optional Often the catches set a variable that the finally checks to see what cleanup is needed

Copyright © Curt Hill Multiple trys and catches There can be as many try catch statements as wanted The smaller the area protected, the more specific the exception handling can be The larger the area the more general the exception handling

Copyright © Curt Hill Throw and Throw Again A catch may end up with an exception that it does not know how to handle It merely issues a throw and lets someone else handle it It better be nested in an if so that all exceptions are not thrown

Copyright © Curt Hill User Defined Exceptions Like most classes Exception may be subclassed Its subclasses may be also A new Exception class may be defined by subclassing any of these and providing both constructors

Copyright © Curt Hill Throwable Exception is a subclass of Throwable Throwable defines most of the methods: –getMessage –printStackTrace Throwable has another subclass Error –Used for problems that most programs will not catch, such as VirtualMachineError

Copyright © Curt Hill Last Thoughts How do you figure out what exceptions to catch? The documentation always specifies any thrown exceptions There is also the trial and error method –Make the last catch for Exception –Exceptions have a toString method –Display this and it will tell you what you should be catching

Copyright © Curt Hill New Things Keywords –try –catch –throw –throws –finally Classes –Exception and descendents