Handling Exceptions. Introduction. Using the Program Halt Handler CHAPTER 10

Similar documents
SCL Arrays. Introduction. Declaring Arrays CHAPTER 4

Data Representation. Variable Precision and Storage Information. Numeric Variables in the Alpha Environment CHAPTER 9

Error Trapping Techniques for SCL. Andrew Rosenbaum, Trilogy Consulting, Kalamazoo, MI

Changes and Enhancements

APPENDIX 2 Customizing SAS/ASSIST Software

Chapter 28 Saving and Printing Tables. Chapter Table of Contents SAVING AND PRINTING TABLES AS OUTPUT OBJECTS OUTPUT OBJECTS...

Formats. Formats Under UNIX. HEXw. format. $HEXw. format. Details CHAPTER 11

Chapter 2 User Interface Features. networks Window. Drawing Panel

Chapter 3 Managing Results in Projects. Chapter Table of Contents

Introduction. LOCK Statement. CHAPTER 11 The LOCK Statement and the LOCK Command

Permission Program. Support for Version 6 Only. Allowing SAS/SHARE Client Access to SAS Libraries or Files CHAPTER 40

Chapter 25 PROC PARETO Statement. Chapter Table of Contents. OVERVIEW SYNTAX SummaryofOptions DictionaryofOptions...

Chapter 6 Creating Reports. Chapter Table of Contents

Using Cross-Environment Data Access (CEDA)

Examples That Use Remote Objecting

Informats. Informats Under UNIX. HEXw. informat. $HEXw. informat. Details CHAPTER 13

Chapter 23 Animating Graphs. Chapter Table of Contents ANIMATING SELECTION OF OBSERVATIONS ANIMATING SELECTED GRAPHS...347

SAS I/O Engines. Definition. Specifying a Different Engine. How Engines Work with SAS Files CHAPTER 36

Using Data Transfer Services

Graphics. Chapter Overview CHAPTER 4

Storing and Reusing Macros

CHAPTER 7 Using Other SAS Software Products

DBLOAD Procedure Reference

Data Set Options. Specify a data set option in parentheses after a SAS data set name. To specify several data set options, separate them with spaces.

Overview. CHAPTER 2 Using the SAS System and SAS/ ASSIST Software

CHAPTER 7 Examples of Combining Compute Services and Data Transfer Services

Using the SQL Editor. Overview CHAPTER 11

Routing the SAS Log and SAS Procedure Output

CHAPTER 13 Importing and Exporting External Data

Macro Facility. About the Macro Facility. Automatic Macro Variables CHAPTER 14

Chapter 7 File Access. Chapter Table of Contents

SAS File Management. Improving Performance CHAPTER 37

Changes and Enhancements to the SAS Component Language (SCL)

SYSTEM 2000 Essentials

Creating and Executing Stored Compiled DATA Step Programs

SAS Web Infrastructure Kit 1.0. Overview

SAS Support for TELNET on Windows

The EXPLODE Procedure

External Files. Definition CHAPTER 38

10 The First Steps 4 Chapter 2

from the source host, use the FTP put command to copy a file from the source host to the target host.

Chapter 25 Editing Windows. Chapter Table of Contents

Alternative ODS HTML Statements for Running Examples in Different Operating Environments

Tasks Menu Reference. Introduction. Data Management APPENDIX 1

SAS Workflow Manager 2.2: Administrator s Guide

Introduction. CHAPTER 3 Working in the SAS Windowing Environment

Introduction to MDDBs

Using SAS Files. Introduction CHAPTER 5

SAS Catalogs. Definition. Catalog Names. Parts of a Catalog Name CHAPTER 32

The SERVER Procedure. Introduction. Syntax CHAPTER 8

DATA Step Debugger APPENDIX 3

Using Unnamed and Named Pipes

SAS IT Resource Management 3.3

SAS/ASSIST Software Setup

QUEST Procedure Reference

Introduction. Getting Started with the Macro Facility CHAPTER 1

SAS. IT Service Level Management 2.1: Migration Documentation

The G4GRID Procedure. Introduction APPENDIX 1

The GREMOVE Procedure

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

OpenVMS Operating Environment

OS/390 Platform Examples

The correct bibliographic citation for this manual is as follows: SAS Institute Inc Proc EXPLODE. Cary, NC: SAS Institute Inc.

Licensing SAS DataFlux Products

SAS Data Libraries. Definition CHAPTER 26

Chapter 14 Introduction to the FACTEX Procedure

UNIX Spawner Program. Starting the UNIX Spawner Program CHAPTER 36

APPENDIX 4 Migrating from QMF to SAS/ ASSIST Software. Each of these steps can be executed independently.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 27 Saving and Printing Graphics

Chapter 9 Selected Examples. Queues with Reneging

Enterprise Miner Software: Changes and Enhancements, Release 4.1

SAS Business Rules Manager 1.2

Loading Data. Introduction. Understanding the Volume Grid CHAPTER 2

OS/2: SPX Access Method

The TRANTAB Procedure

SAS Infrastructure for Risk Management 3.4: User s Guide

UNIX Platform Error Messages

Using Dynamic Data Exchange

Formats. SAS Formats under OpenVMS. Writing Binary Data CHAPTER 13

SAS 9.2 Foundation Services. Administrator s Guide

Windows: SPX Access Method

Locking SAS Data Objects

SAS Model Manager 2.2. Tutorials

Chapter 28 Command Reference. Chapter Table of Contents TSVIEW COMMAND FORECAST COMMAND

The SAS Interface to REXX

Executing SAS/AF Applications

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

SAS/Warehouse Metadata API. Reference Second Edition

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

The TIMEPLOT Procedure

Using MDP Extensions. What Is the Multidimensional Data Provider? CHAPTER 3

Batch Importing. Overview CHAPTER 4

SAS/FSP 9.2. Procedures Guide

Using CVS Repositories with SAS

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

The STANDARD Procedure

Introduction. Understanding SAS/ACCESS Descriptor Files. CHAPTER 3 Defining SAS/ACCESS Descriptor Files

Chapter 15 Mixed Models. Chapter Table of Contents. Introduction Split Plot Experiment Clustered Data References...

SAS Clinical Data Integration 2.4

Transcription:

157 CHAPTER 10 Handling Exceptions Introduction 157 Using the Program Halt Handler 157 Handling Exceptions with CATCH and THROW 158 Example 160 How SCL Determines Which CATCH Block To Execute 160 Catching and Rethrowing Exceptions 162 Nested CATCH Blocks 163 The SCLThrowable and SCLException Classes 163 Introduction SCL provides two mechanisms for handling error conditions: The program halt handler Program halt handlers typically allow your application to print a message, save some information, and then either try to continue execution or halt the application. The SCL generic program halt handler is sort of an all-purpose routine for handling program halts that occur for a variety of different reasons at any point in the program. The CATCH and THROW statements The SCLException class and the CATCH and THROW statements enable you to define specific exceptions and recovery routines that are specific to each exception. You can define the exceptions and recovery routines in the locations in your code where the exceptions may be encountered, thus making error recovery code a natural part of the program. Using the Program Halt Handler The program halt handler is designed to handle unexpected run-time errors. The programhalt class contains methods that are called when certain run-time exceptions occur. By overriding these methods, you can specify whether an application should halt immediately or continue executing. You can control how exceptions are handled. In the following example, the _ongeneric method creates a list named MSGS, inserts information about the location where the application failed into the list, and displays the list with the MESSAGEBOX function. You can use this code to create your own program halt handler. class myhalt extends sashelp.classes.programhalt.class;

158 Handling Exceptions with CATCH and THROW 4 Chapter 10 _ongeneric:method / (STATE= O ); dcl list msgs=makelist(); rc = insertc(msgs, "SCL program failed at ", 1); rc = insertc(msgs, "Entry=" entry, 2); rc = insertc(msgs, "Line=" putn(linenumber, "3.0"), 3); if (keywordtype = function ) then rc = insertc(msgs, "Function=" keyword, 4); else rc = insertc(msgs, "Method=" keyword, 4); rc = messagebox(msgs); /* continue execution */ stopexecution = No ; Note: Entry, linenumber, keyword, and keywordtype are all object attributes that are defined in the class sashelp.classes.programhalt.class. 4 The _ongeneric method traps any error messages that are generated by SCL and saves them in the MSGS list. Developers can use this list to identify and fix potential problems in their code. The programhalt handler must be declared at the beginning of your application. For example: dcl myhalt obj = _new_ myhalt(); Your program can instantiate multiple programhalt handlers, or your program may instantiate only one handler, but then call a second program that instantiates its own handler. The last programhalt handler that is instantiated is the current programhalt handler. Only the current programhalt handler is active at any one time. SCL uses a stack to keep track of programhalt handlers. Each time a programhalt handler is instantiated, the new instance is pushed onto the stack. The handler on the top of the stack is always the active handler. Before a program terminates it must terminate (using the _term method) its programhalt handler. For example: obj._term(); Terminating a programhalt handler pops it from the stack, and makes the next programhalt handler on the stack the active handler. For example, if your program instantiates the programhalt handler, and then calls another SCL program, the second program may also instantiate a programhalt handler. The second programhalt handler becomes the current programhalt handler. Before the second program ends, it must terminate the second programhalt handler. The first programhalt handler then becomes the current programhalt handler. If the second programhalt handler is not terminated, it will remain active even after the program that instantiated it has terminated. Handling Exceptions with CATCH and THROW All exceptions are subclasses of the SCLException class, which is a subclass of the SCLThrowable class. You can use the CLASS statement to define your own exception classes, and then use the THROW and CATCH statements to handle the exception. Because an exception is a class, you can design the class to contain any information that is relevant to recovering from the specific exception. A simple exception class may

4 Handling Exceptions with CATCH and THROW 159 contain only an error message. For example, the following class defines a subclass of SCLException called NewException, which defines an error message string named SecondaryMessage: Example Code 10.1 NewException Class Class NewException extends SCLException dcl string SecondaryMessage; You can then create a new instance of NewException and raise this exception with the THROW statement,as shown in the ThrowIt class: Example Code 10.2 ThrowIt Class Class ThrowIt; m: method; dcl NewException NE = _new_ NewException( Exception in method m ); NE.SecondaryMessage = "There s no code in m!"; throw NE; Note: You must always declare a variable to hold the thrown exception. 4 The code that processes the exception is enclosed in CATCH blocks. CATCH blocks can contain any code needed to process the exception, including more CATCH and THROW statements. When an exception is thrown, normal execution of the entry stops, and SCL begins looking for a CATCH block to process the thrown class. The CATCH block can contain any statements needed to process the exception. For example, the following code prints the stack traceback at the point of the throw. dcl NewException NE = new NewException( Exception in method m ); NE.SecondaryMessage = "There s no code in m!"; throw NE; catch NE; put NE.getMessage(); /* Print exception information. */ call putlist(ne.traceback); put NE.SecondaryMessage=; /* Print secondary message. */ Note: CATCH blocks must always be enclosed in DO statements. 4 The traceback information that is printed by this example is stored automatically by SCL when an exception is thrown. See The SCLThrowable and SCLException Classes on page 163 for more information. Note: When a CATCH block has finished executing, control transfers to the end of the current DO statement, and the program resumes normal execution. If no exception has been thrown and SCL encounters a CATCH block, control transfers to the end of the current DO statement and execution resumes at that location. Therefore, any SCL statements the occur between CATCH blocks or following the last CATCH block within the same DO group will never be executed. Any SCL statements within the DO group that are not part of a CATCH block but must execute must be entered at the beginning of the DO group. 4

160 Example 4 Chapter 10 After an exception is processed, program execution continues normally. Example Suppose you have the following class Y. This class defines a method called update that throws an exception that is an instance of the SCLException class. import sashelp.classes; class Y; update: method; if (_self_.readonly) then /* Throw an exception. Set message via constructor. */ throw _new_ SCLException( Cannot update when in ready-only mode ); Class X defines method M, which declares a local variable to hold the exception, and then calls the update method, which throws the exception. The exception is then processed by the CATCH block for SCLE. import sashelp.classes; class X; M: method; /* Declare the local exception variable. */ dcl SCLException scle; dcl Y y = _new_ y(); /* Call update method, which throws SCLEception. */ y.update(); /* Process the SCLException. */ catch scle; /* Print exception information. */ put scle.getmessage(); call putlist(scle.traceback); How SCL Determines Which CATCH Block To Execute SCL uses the scope of the DO group that contains the CATCH block and the class of the exception to determine which CATCH block to execute. 3 SCL first looks in the scope of the DO group where the exception was initially thrown. If SCL does not find a corresponding CATCH block, it expands its search outward to the next enclosing DO group. Note: If you are rethrowing an exception that has been thrown and caught at least once already, then SCL automatically passes the exception outside of the DO group where the exception was rethrown. 4 SCL continues expanding the scope of its search until it finds a corresponding CATCH block or it has searched the current SCL entry. If the current SCL entry

4 How SCL Determines Which CATCH Block To Execute 161 does not contain a CATCH block for the thrown class, then the exception is passed up the stack to the calling entry where the process is repeated. If the calling entry contains a CATCH statement for the thrown class, then execution resumes at the location of the CATCH statement. If the calling entry does not contain a CATCH statement for the thrown class, then the exception is passed up the stack until SCL finds a corresponding CATCH statement or until the stack is completely unwound. If SCL does not find a corresponding CATCH statement, then the exception is treated the same as a program halt. 3 SCL uses the class hierarchy to determine which CATCH block to execute. Within the scope that it is currently searching, SCL chooses the CATCH block for the class that is most closely related to the class of the thrown exception. For example, if the current scope contains a CATCH block for the thrown class, then SCL will execute that CATCH block. If the current scope does not contain a CATCH block for the thrown class, but does contains a CATCH block for the parent class of the thrown exception, then SCL will execute the CATCH block for the parent class. If none of the CATCH blocks in the current scope are related to the thrown class, then SCL continues its search for an appropriate CATCH block. Suppose that in addition to the NewException class (see Example Code 10.1 on page 159) you define a subclass of NewException called SubException: Example Code 10.3 SubException Class Class SubException extends NewException...code to process SubExceptions... As with all exceptions, SCL first searches the current DO group for a CATCH block that is related to the thrown class. In this example, because NEsub is an instance of SubException and SubException is a subclass of NewException, SCL will execute the CATCH block for NE because it is in the scope of the current DO group. The CATCH block for NEsub is in a different scope (the outer DO group), so it will not be executed unless the CATCH block for NE is modified to rethrow (see Catching and Rethrowing Exceptions on page 162) the exception. If the CATCH block for NE rethrows the exception, then both CATCH blocks will be executed. Example Code 10.4 Nested DO Statements dcl NewException NE; dcl SubException NEsub; NEsub = _new_ SubException( Exception in method m ); NEsub.SecondaryMessage = "There s no code in m!"; throw NEsub; catch NE; put NE.getMessage(); /* Print exception information. */ call putlist(ne.traceback); put NE.SecondaryMessage=; /* Print secondary message. */ /* Could rethrow the NEsub exception if needed. */ /* The following CATCH block will not be executed */ /* unless the CATCH block for NE rethrows the exception. */

162 Catching and Rethrowing Exceptions 4 Chapter 10 catch NEsub;...code to process NEsub exceptions... Catching and Rethrowing Exceptions Each entry in the stack can process an exception and then pass it back up the stack by rethrowing it, which allows the calling entry to perform additional processing. Each entry can perform whatever processing is relevant to that entry. catch e1;...process the exception... throw e1; /* Rethrow the exception. */ Note: If an exception is rethrown within a CATCH block, no CATCH block within the same scope can recatch the exception. The exception is passed out of the scope where it was thrown. 4 If SCL finds a second CATCH block for E1 within the same SCL entry but outside of the scope of the DO group where the exception was thrown, then execution continues with that second CATCH block. If SCL does not find another CATCH block for E1 in that same SCL entry, then the exception is passed up the stack to the calling entry. Suppose you have defined the NewException class (see Example Code 10.1 on page 159) and the ThrowIt class (see Example Code 10.2 on page 159). The following program section calls method M, which throws the exception NE. The two CATCH blocks catch, rethrow, and recatch the exception. init: dcl ThrowIt TI = _new_throwit(); dcl NewException NE; TI.m(); catch NE; put caught it ; throw NE; catch NE; put caught it again ; return; Note: You cannot define multiple CATCH blocks for the same exception within the same scope. 4

4 The SCLThrowable and SCLException Classes 163 Nested CATCH Blocks You can nest CATCH blocks. For example, suppose you define the class W as follows: class w; m: method n:num; dcl e1 e1; dcl e2 e2; if (n < 0) then throw _new_ e2(); else throw _new_ e1(); catch e2; put caught inner e2 ; dcl e1 e1; if (n<0) then throw _new_ e2(); else throw _new_ e1(); catch e1; put caught inner e1 ; catch e1; put caught outer e1 ; catch e2; put caught outer e2 ; If you invoke method M with a negative argument as in the following program section: init: dcl w w = _new_ w(); w.m(-2); return; then the output would be caught inner e2 caught outer e2 The SCLThrowable and SCLException Classes All exceptions are subclasses of the SCLException class, which is a subclass of the SCLThrowable class. When an exception is thrown, SCL automatically stores the name of the entry that throws the exception, the line number where the throw occurs, and the stack traceback at the point of the throw. You can set the message attribute via the

164 The SCLThrowable and SCLException Classes 4 Chapter 10 constructor when an instance of the exception is created. You can use the getmessage method to return the message. Example Code 10.5 SCLThrowable Class class SCLThrowable; public string(32767) message; public list traceback; /* stack traceback */ public string entry; /* SCL entry name */ public num line; /* line number */ SCLThrowable: public method s:string; message = s; getmessage: public method return=string; return message; Example Code 10.6 SCLException Class class SCLException extends SCLThrowable; SCLException: public method /(state= o ); _super("sclexception"); SCLException: public method s:string /(state= o ); _super(s);

The correct bibliographic citation for this manual is as follows: SAS Institute Inc., SAS Component Language: Reference, Version 8, Cary, NC: SAS Institute Inc., 1999. SAS Component Language: Reference, Version 8 Copyright 1999 by SAS Institute Inc., Cary, NC, USA. ISBN 1 58025 495 0 All rights reserved. Produced in the United States of America. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, or otherwise, without the prior written permission of the publisher, SAS Institute Inc. U.S. Government Restricted Rights Notice. Use, duplication, or disclosure of the software and related documentation by the U.S. government is subject to the Agreement with SAS Institute and the restrictions set forth in FAR 52.227 19 Commercial Computer Software-Restricted Rights (June 1987). SAS Institute Inc., SAS Campus Drive, Cary, North Carolina 27513. 1st printing, October 1999 SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. indicates USA registration. Other brand and product names are registered trademarks or trademarks of their respective companies. The Institute is a private company devoted to the support and further development of its software and related services.