Java Exceptions, Cloning, Serialization Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.

Slides:



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

CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
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.
COMP 121 Week 5: Exceptions and Exception Handling.
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.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
For use of Cleveland State's IST410 Students only 1 Exception.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
交通大學資訊工程學系 Programming in Java Exception Handling 蔡文能 交通大學資訊工程學系
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.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
12.1 Exceptions The limitations of traditional methods of exception handling Error conditions are a certainty in programming Programmers make.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
COMP Exception Handling Yi Hong June 10, 2015.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
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.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
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.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
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.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Java Exceptions a quick review….
CS102 – Exceptions David Davenport Latest: May 2015
Exception Handling in Java
Web Design & Development Lecture 7
Exceptions 10-May-19.
Exception Handling and Event Handling
Exception Handling.
Presentation transcript:

Java Exceptions, Cloning, Serialization Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Overview Review Errors Exceptions Java support Representing exceptions Generating & handling exceptions Designing & using exceptions

Types of Program Errors 1. Syntax (compiler) errors Errors in code construction (grammar, types) Detected during compilation 2. Run-time errors Operations illegal / impossible to execute Detected during program execution Treated as exceptions in Java 3. Logic errors Operations leading to incorrect program state May (or may not) lead to run-time errors Detect by debugging code

Exception Handling Performing action in response to exception Example actions Ignore exception Print error message Request new data Retry action Approaches 1. Exit program 2. Exit method returning error code 3. Throw exception

Problem May not be able to handle error locally Not enough information in method / class Need more information to decide action Handle exception in calling function(s) instead Decide at application level (instead of library) Examples Incorrect data format  ask user to reenter data Unable to open file  ask user for new filename Insufficient disk space  ask user to delete files Will need to propagate exception to caller(s)

Exception Handling – Exit Program Approach Exit program with error message / error code Example if (error) { System.err.println(“Error found”);// message System.exit(1);// error code } Problem Drastic solution Event must be handled by user invoking program Program may be able to deal with some exceptions

Exception Handling – Error Code Approach Exit function with return value  error code Example A( ) { if (error) return (-1); } B( ) { if ((retval = A( )) == -1) return (-1); } Problems Calling function must check & process error code May forget to handle error code May need to return error code to caller Agreement needed on meaning of error code Error handling code mixed with normal code

Exception Handling – Throw Exception Approach Throw exception (caught in parent’s catch block) Example A( ) { if (error) throw new ExceptionType(); } B( ) { try { A( ); } catch (ExceptionType e) {...action... } } Java exception backtracks to caller(s) until matching catch block found

Exception Handling – Throw Exception Advantages Compiler ensures exceptions are caught eventually No need to explicitly propagate exception to caller Backtrack to caller(s) automatically Class hierarchy defines meaning of exceptions No need for separate definition of error codes Exception handling code separate & clearly marked

Representing Exceptions Exceptions represented as Objects derived from class Throwable Code public class Throwable( ) extends Object { Throwable( )// No error message Throwable( String mesg )// Error message String getMessage()// Return error mesg void printStackTrace( ) { … }// Record methods …// called & location }

Representing Exceptions Java Exception class hierarchy Two types of exceptions  checked & unchecked

Object Error Throwable Exception LinkageError VirtualMachoneError ClassNotFoundException CloneNotSupportedException IOException AWTError … AWTException RuntimeException … ArithmeticException NullPointerException IndexOutOfBoundsException Unchecked Checked NoSuchElementException … Representing Exceptions Java Exception class hierarchy

Unchecked Exceptions Class Error & RunTimeException Serious errors not handled by typical program Usually indicate logic errors Example NullPointerException, IndexOutOfBoundsException Catching unchecked exceptions is optional Handled by Java Virtual Machine if not caught

Checked Exceptions Class Exception (except RunTimeException) Errors typical program should handle Used for operations prone to error Example IOException, ClassNotFoundException Compiler requires “catch or declare” Catch and handle exception in method, OR Declare method can throw exception, force calling function to catch or declare exception in turn Example void A( ) throws ExceptionType { … }

Generating & Handling Exceptions Java primitives Try Throw Catch Finally Procedure for using exceptions 1. Enclose code generating exceptions in try block 2. Use throw to actually generate exception 3. Use catch to specify exception handlers 4. Use finally to specify actions after exception

Java Syntax try {// try block encloses throws throw new eType1(); // throw jumps to catch } catch (eType1 e) { // catch block 1...action... // run if type match } catch (eType2 e) { // catch block 2...action... // run if type match } finally { // final block...action... // always executes }

Java Primitive – Try Forms try block Encloses all statements that may throw exception Scope of try block is dynamic Includes code executed by methods invoked in try block (and their descendents)

Java Primitive – Try Example try {// try block encloses all exceptions in A & B A( ); // exceptions may be caught internally in A & B B( ); // or propagated back to caller’s try block } void A( ) throws Exception { // declares exception B( ); } void B( ) throws Exception { // declares exception throw new Exception( ); // propagate to caller }

Java Primitive – Throw Indicates exception occurred Normally specifies one operand Object of class Exception When an exception is thrown 1. Control exits the try block 2. Proceeds to closest matching exception handler after the try block 3. Execute code in exception handler 4. Execute code in final block (if present)

Java Primitive – Catch Placed after try block Specifies code to be executed for exception Code in catch block  exception handler Catch block specifies matching exception type Can use multiple catch blocks for single try To process different types of exceptions First matching catch block executed Superclass may subsume catch for subclass If catch block for superclass occurs first

Java Primitive – Catch Example class eType1 extends Exception { … } try { … throw new eType1( ) … } catch (Exception e) { // Catch block 1...action... // matches all exceptions } catch (eType1 e) { // Catch block 2...action... // matches eType1 } // subsumed by block 1 // will never be executed

Java Primitive – Catch Can rethrow exception Exception propagated to caller(s) Example catch (ExceptionType e) { …// local action for exception throw e; // rethrow exception }// propagate exception to caller

Java Primitive – Finally Placed after try & all catch blocks Forms finally block Cleanup code Executed by all exception handlers Try restore program state to be consistent, legal Always executed Regardless of which catch block executed Even if no catch block executed Executed before transferring control to caller If exception is not caught locally

Designing & Using Exceptions Use exceptions only for rare events Not for common cases  checking end of loop High overhead to perform catch Place statements that jointly accomplish task into single try / catch block Use existing Java Exceptions if possible

Designing & Using Exceptions Avoid simply catching & ignoring exceptions Poor software development style Example try { throw new ExceptionType1( ); throw new ExceptionType2( ); throw new ExceptionType3( ); } catch (Exception e) { // catches all exceptions … // ignores exception & returns }

Exceptions Summary Java primitives Try Forms try block Encloses all statements that may throw exception Throw Actually throw exception Catch Catches exception matching type Code in catch block  exception handler Finally Forms finally block Always executed, follows try block & catch code

Exceptions Summary Programs often contain errors Exceptions  advanced Java language feature Java provides detailed support for exceptions Learn to use exceptions carefully

Java – Cloning Cloning Creating an identical copy Cloneable interface Supports clone( ) method Returns copy of object Copies all of its fields Does not clone its fields Makes a shallow copy

Java – Cloning Effect of clone( ) Creates new object X.clone( ) != X Same class X.clone.getClass( ) == X.getClass( ) Modification to X no longer affect X.clone( )

Java Clone Comparison Example (X.f = Z) X X.f = Z X Z XX Z

Java Clone Comparison Example (X.f = Z) Y = X XY Y = X.clone( ) X Y ZZ X, YXY

Java Clone Comparison Example (X.f = Z) Y = X; X.f = A XY Y = X.clone( ); X.f = A X Y AZA XYX, Y

Java – Serializability Serializability Ability to convert a graph of Java objects into a stream of data, then convert it back (deserialize) Java.io.Serializable interface Marks class as Serializable Supported by Java core libraries Special handling (if needed) using private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException ; Makes a deep copy

Serializability – Uses Persistance Using FileOutputStream Store data structure to file for later retrieval Copy Using ByteArrayOutputStream Store data structure to byte array (in memory) and use it to create duplicates Communication Using stream from a Socket Send data structure to another computer

Serializability – Deep Copy // serialize object ByteArrayOutputStream mOut = new ByteArrayOutputStream( ); ObjectOutputStream serializer = new ObjectOutputStream(mOut); serializer.writeObject(serializableObject); serializer.flush( ); // deserialize object ByteArrayInputStream mIn = new ByteArrayInputStream(mOut. toByteArray( )); ObjectInputStream deserializer = new ObjectInputStream(mIn); Object deepCopyOfOriginalObject = deserializer.readObject( );

Java Serializable Comparison Example (X.field = Z) Y = X XY Y = X.clone( ) X Y ZZ X, Y X Y OS.writeObject(x) Y = readObject(IS) X Y Z X Y Z’