Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.

Slides:



Advertisements
Similar presentations
Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
Advertisements

Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
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.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
CS April 2010 Exceptions in Java. Read chapter 10. HUMOR FOR LEXOPHILES (LOVERS OF WORDS): Police were called to a day care; a three-year-old was.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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.
MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
CSE 11 February 11, © 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
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 Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with 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.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
AP Java 1/14/2016 Inheritance Review. Learning Objectives Be able to understand how to create classes that use inheritance. Be able to dry run programs.
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:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Generics, Exception and Undo Command. A Generic Stack Class AStack uses generic. In the main method, we have 2 instances of AStack, each type is Integer.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Java Programming Language
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Handling Exceptions.
Exception Handling Chapter 9.
Exceptions & exception handling
ATS Application Programming: Java Programming
Exceptions & exception handling
CMSC 202 Exceptions 2nd Lecture.
Exception Handling in Java
Presentation transcript:

Exceptions Session 21

Memory Upload Creating Exceptions Using exceptions to control object creation and validation

Exceptions To create exceptions we need to extend the Exception class The exception class has one instance variable

Checked Exceptions A checked exception must:  Be caught  Be listed in the throws clause of the method where it may occur

Unchecked Exceptions An unchecked are:  Descendants of the RuntimeException

Exception public class MyException extends Exception{ private String message; public MyException( ){ //empty constructor } public void setMessage(String newMsg){ this.message = newMsg; } public String getMessage( ){ return this.message; } } constructor set method get method

The “Other” Class The class with the main method is called the driver class We create a class that can throw an exception

The “Other” Class public class ExcThr{ public static void main(String [ ] arg) throws Exception{ MyException me = new MyException( ); throw me; } //main method } //class ends

The “Other” Class public class ExcThr{ public static void main(String [ ] arg) throws Exception{ MyException me = new MyException( ); me.setMessage(“ICS111 Exception”); throw me; } //main method } //class ends

Exception Propagation If an exception is not caught and handled where it occurs it will propagate back to the source. In applications this will be the main method.

Running Several Classes All classes must be in the same directory When compiling a class that uses others Java will automatically find the other classes. This applies to exceptions as well

Time to Try it Out Creating and throwing exceptions. Exception messages

Why do that? You can create exceptions to make your classes independent. Think:  How can you prevent users from creating invalid objects? User, please do not create invalid objects

Where is the validation? We can validate in the driver class. This makes the Name class dependent in another class So what can we do? Throw an exception within the Name class!!!!

A simple class public class Name{ String name = “”; public Name(String name){ this.name = name; } public String getName( ){ return this.name; } constructor get method

A simple class public void setName(String newName){ this.name = name; } public String toString( ){ String s = “Name: ”+ this.name; return s; } } //class name ends set method toString method

Creating a Name Exception Write down the rules for a valid name.  Name needs to be at least 3 characters long  Name cannot be blank

Creating a Name Exception So the exception will be thrown if:  Name is composed of only blanks even if it is longer than 2 characters  Name is less than 3 characters long. Lets translate the rules into Java

NameException public class NameException extends Exception{ private String message; public NameException( ){ //empty constructor } public void setMessage(String newMsg){ this.message = newMsg; } public String getMessage( ){ return this.message; } } constructor set method get method

Name Class Modifications //the constructor changes public Name(String name) throws Exception{ this.name = this.setName(name); } The strategy? Centralized validation

Name Class Modifications public void setName(String newName ) throws Exeption{ int len = 0; newName = newName.trim( ); len = newName.length( ); if(len<3){ NameException ne = new NameException( ); ne.setMessage(“Invalid name length”); throw ne; } this.name = newName; }

Name Class Modifications public String getName( ){ return this.name; } public String toString( ){ String s = “Name: ”+ this.name; return s; } } //class name ends Not in these methods

The Driver Class public class UsingNames{ public static void main(String [ ] arg) throws Exception{ Name n1 = new Name(“ABC”); System.out.println(n1.toString( )); Name n2 = new Name(“ W ”); System.out.println(n1.toString( )); } } ABC

Name Class Modifications public void setName(String newName ) throws Exeption{ int len = 0; newName = newName.trim( ); len = newName.length( ); if(len<3){ NameException ne = new NameException( ); ne.setMessage(“Invalid name length”); throw ne; } this.name = newName; } ABC 3

The Driver Class public class UsingNames{ public static void main(String [ ] arg) throws Exception{ Name n1 = new Name(“ABC”); System.out.println(n1.toString( )); Name n2 = new Name(“ W ”); System.out.println(n1.toString( )); } } W

Name Class Modifications public void setName(String newName ) throws Exeption{ int len = 0; newName = newName.trim( ); len = newName.length( ); if(len<3){ NameException ne = new NameException( ); ne.setMessage(“Invalid name length”); throw ne; } this.name = newName; } W W Exception 1

Exception Propagation NameException String message Constructor NameException( ) String getMessage( ) void setMessage(String newMessage) Name String name Constructor Name(String name) String getMessage( ) void setMessage(String newMessage) UsingNames void main(String arg) Exception Class Created by JAVA Exception

One Exception Several Messages One Exception can display several messages as the program crashes The message can be set on each of the different methods that may throw the exception

Validation in set methods The methods that validate are usually the set methods. The constructor validates by calling on the set methods Each set method can add a different exception message in case of error.

Exceptions in Applets

Time to Try it Out Exceptions and Objects

Creating Exceptions Setting exception messages Validating objects using our own exceptions any questions to Memory Defragmenter

Task Manager Answer the 5 webct questions Read your Visit WebCT, webct.hawaii.edu