`

c++ function try block

    博客分类:
  • c++
c++ 
阅读更多

function try block is a block which the entire body of the function body is encosed in a try cluase block;

 

for better illustration, let see some examples which can better serve for our dicussion purpose later on the exception handling issues. 

 

Let's first introduce the the test code that we are going to use, it is a home made iStack class; 

 

the header file of the stackExcp.h is as follow.

 

 

/***
* @summary
*  stackExcep.h is the header file that define the class that is called iStack, which we will use as the data object to manipulate and demonstate the use 
* of exception in C++
*/

#include <vector>
using std::vector;

class iStack 
{
public : 
	iStack(int capacity ) : _stack(capacity) , _top(0) { }
	void pop(int & top_value) ;
	void push (int value);

	bool full();
	bool empty();
	void display();

	int size();

private: 
	int _top;
	vector <int> _stack;
};


/**
* @Summary
* to demonstrate the use of Exception, we are going to define two classes, one is the 
*    popOnEmpty()
* the other is 
*    pushOnFull
*/
class popOnEmpty { /* ....  */ };

class pushOnFull { /* ... */ };

 

 

part of the stackExcp.'s implementation is as follow.

 

 

#include "stackExcp.h"
#include <iostream>
using std::cout;
using std::endl;

void iStack::pop(int &top_value)
{
	if (empty()) 
	{
		throw popOnEmpty();
	}
	top_value = _stack[--_top];
	cout << "istack::pop(): " << top_value << endl;
}


void iStack::push(int value)
{
	cout << "istack::push( " << value << " ) \n";
	if (full()) 
	{
		throw pushOnFull();
	}
	_stack[_top++] = value;

}

bool iStack::empty()
{
	return _top <= 0;
}

bool iStack::full()
{
	return _top > _stack.capacity(); // a common pitfall is tha the use _stack.size();
}

void iStack::display()
{
	cout << "display: ( ";
	for (int i = 0; i < _top; ++i)
	{
		// a common case of error is that if you write as follow
		// the code will be like this:
		//   cout << _stack[i} << ( i == _top - 1) ? ")" : "";
		// it will output some wierd output , guess the compiler try to output the value of the condition test part of the  the ternary expression
		// that is because of the order of the execution , 
		// where the ?: has a lower precedence than the << operator
		// so it will first output the evalution value of the condition expression and then if depends on the return resutlt, which is a 

		cout << _stack[i] << " " << ((i == _top - 1) ? " )" : "") ;
		if (i != 0 && i % 8 == 0 || i == _top - 1 ) cout << endl;
	}

}

 

normally we will write c++ code as follow :

 

 

void intermixedTryClause()
{
	iStack stack(32);

	for (int ix = 0;ix < 51; ++ix)
	{
		try 
		{
			if (ix % 3 == 0) {
				stack.push(ix);
			}
		}
		catch (pushOnFull) 
		{
			//cout << "caught error on pushOnFull" << endl;
		}
		if (ix % 4 == 0) 
		{
			stack.display();
		}


		try 
		{
			if (ix % 10 == 0)
			{
				int dummy;
				stack.pop(dummy);
				stack.display();
			}
		}
		catch (popOnEmpty) 
		{
			//cout << "caught error on popOnEmpty" << endl;
		}
	}
}
 

as you can see we intermix the body of the function with that of exception handling, which does not follow the separation rule that implementation code should be separated from its error handling code.

 

 

there is a small technique that you can try to make the function body more fun, which as many reader has figured out, it is the function try block, let's see how it works out.

 

 

 

/**
* Below test the function try body techniques where you can put the try clause with the catch clauses right after the function body without 
* the function opening body '{' or the function closing body '}'
*/
void functionTryBody() try 
{
	 iStack stack(32);
	 for (int i = 0; i < 51; ++i ) {
		 int val;
		 if (i % 3 == 0) stack.push(i);
		 if (i % 4 == 0) stack.display();
		 if (i % 10 == 0) { stack.pop(val); stack.display(); } 
	 }
}
catch (popOnEmpty) { /* */ } 
catch (pushOnFull) { /* */ }
 

so directly follow the function declaration is the try keyword , then is the try body followed by several catch handlers and body;

 

 

 

分享到:
评论

相关推荐

    C++代码规范.rar

    函数定义和参数之间用空格隔开,如` void function(int arg1, int arg2) `;操作符两侧也应有空格,如` a + b `。 接着,注释是代码规范中的关键元素,它能帮助其他开发者理解代码的功能和逻辑。注释应简洁明了,...

    C++编码规范与指导

    2. 函数名:小写字母和下划线组合,如`my_function`。 3. 变量名:遵循函数名的规则,但常量全用大写字母,如`MY_CONSTANT`。 4. 命名空间:使用小写字母和下划线,如`my_namespace`。 5. 避免使用保留字,避免误导...

    21天学通C++.21天学通C++.21天学通C++.21天学通C++.

    - 虚函数:`virtual void function();` - 重写:派生类中覆盖基类的虚函数。 - 动态绑定:运行时决定调用哪个版本的方法。 - **编译时多态**:通过函数重载和模板实现。 **13. 运算符重载** - **运算符重载**:...

    jquery需要的所有js文件

    b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}});return d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e=b.split(".")[0],f;...

    my97日历控件

    =$dp.el&&$dp.dd.style.display=="block")$dp.cal.close()}catch($){}}function Z(){$dp.status=2}var Q,_;function U(K,C){if(!$dp)return;B();var L={};for(var H in K)L[H]=K[H];for(H in $)if(H.substring(0,1)!...

    网页制作完全手册

    -- Try links with different hookups - should be canceled by "Cancel" to confirm dialog. --&gt; &lt;BR&gt;&lt;A NAME=b1 HREF="http://www.microsoft.com" onclick="askConfirm()"&gt;1 Without return (won't work) &lt;BR&gt;&lt;A ...

    Python 的缩进规则.pdf

    与 C/C++、Java 等语言不同,Python 不使用花括号 `{}` 来界定代码块,而是依赖于代码的缩进层级来决定哪些行属于同一代码块。这种设计不仅使代码更加整洁,还增强了代码的可读性。 #### 三、Python 缩进规则详解 ...

    FastReport 4.8

    - fixed bug when designer place function in commented text block - fixed bug when Engine try to split non-stretcheable view and gone to endless loop - fixed bug with ...

    FastReport4.8.27 for D7-D2010

    - fixed bug when designer place function in commented text block - fixed bug when Engine try to split non-stretcheable view and gone to endless loop - fixed bug with ...

    LLVM-Simple-Wrapper:我们的编译器中使用的简单 LLVM 包装器

    这包括模块(Module)、IRBuilder、函数(Function)、基本块(BasicBlock)等核心概念的封装,使得用户可以通过更直观的方式来操作LLVM IR。 2. **C++模板**:由于C++模板可以实现泛型编程,LLVM-Simple-Wrapper可能会...

    FastReport.v4.8.36 for.Delphi.BCB.Full.Source中文修正版

    - fixed bug when designer place function in commented text block - fixed bug when designer shows commented functions in object inspector - fixed bug when engine delete first space from text in split ...

    CheckMem.pas

    Write(OutFile, BlockSize: 4, '($' + IntToHex(BlockSize, 4) + ')字节', ' - '); try Item := TObject(ObjList[I]); if PTypeInfo(Item.ClassInfo).Kind &lt;&gt; tkClass then { type info technique } write...

    操作系统(内存管理)

    在大部分系统语言中,比如 C 和 C++,您必须进行内存管理。本文将介绍手工的、半手工的以及自动的内存管理实践的基本概念。 追溯到在 Apple II 上进行汇编语言编程的时代,那时内存管理还不是个大问题。您实际上在...

    Squirrel教程

    - **异常处理(Try/Catch)**:用于捕获和处理运行时错误。 - **抛出异常(Throw)**:用于引发异常。 - **常量(Const)**:不可更改的变量。 - **枚举(Enum)**:一组具有名称的常量。 - **表达式语句(Expression ...

    vld(Visual Leak Detector 内存泄露检测工具 源码)

     // Try to get the name of the function containing this program  // counter address.  if (pSymFromAddr(m_process, (*callstack)[frame],  &displacement64, pfunctioninfo)) {  functionname = ...

    ICS delphixe10源码版

    .\Packages (was Delphi\Vc32) Delphi (7 and up) and C++Builder (2006 and up) packages projects .\Source (was Delphi\Vc32) ICS Delphi source code built into packages .\Source\Include (was Delphi\Vc32) ....

    内存管理内存管理内存管理

    /* Include the sbrk function */ #include void malloc_init() { /* grab the last valid address from the OS */ last_valid_address = sbrk(0); /* we don't have any memory to manage yet, so *just ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持Delphi 4-XE5 and C++Builder 6-XE5. D2010以上版本(D14_D19)安装必读 delphi2010以上版本(D14_D19)使用者安装时,请将res\frccD14_...

    VB编程资源大全(英文源码 其它)

    Any open data will try to be saved prior to the shutdown process. &lt;END&gt;&lt;br&gt;80,Close(x)Button.zip With the help of this program one can disable close(x) button of the form. &lt;END&gt;&lt;br&gt;81,DriveSpace....

Global site tag (gtag.js) - Google Analytics