search
HomeBackend DevelopmentPHP Tutorial try catch throw php收集

try catch throw php搜集

我个人的理解是:?
1。在private或者protected的成员函数不使用try,catch,而只使用throw?
2。如果在private或者protected的成员函数需要使用try,catch,那么就要使用rethrow?
3。在public成员函数里使用try,catch?
4。如果该类相对于整个项目来说是属于被调用层,那么public成员函数也可以不使用try,catch?
5。如果调用第三方的代码,我一般都会用try,catch?
class CTest1;?
class CTest2;?
class CTest3;?

void BadCode()?
{?
? //define?
? CTest1 * pTest1 = NULL;?
? CTest2 * pTest2 = NULL;?
? CTest3 * pTest3 = NULL;?

? //使用try, catch, throw?
? try?
? {?
? ? //new test1?
? ? pTest1 = new CTest1;?

? ? //do something?
? ? bool bRet = DoSomething();?
? ? if (!bRet)?
? ? ? throw -1;?

? ? //new CTest2?
? ? pTest2 = new CTest2;?

? ? //do something?
? ? bRet = DoSomething();?
? ? if (!bRet)?
? ? ? throw -2;?

? ? //new CTest3?
? ? pTest3 = new CTest3;?

? ? bRet = DoSomething();?
? ? //do something?
? ? if (!bRet)?
? ? ? throw -3;?

? ? //release?
? ? delete pTest1;?
? ? pTest1 = NULL;?
? ? delete pTest2;?
? ? pTest2 = NULL;?
? ? delete pTest3;?
? ? pTest3 = NULL;?
? }?
? catch(...)?
? {?
? ? if (pTest1)?
? ? ? delete pTest1;?
? ? if (pTest2)?
? ? ? delete pTest2;?
? ? if (pTest3)?
? ? ? delete pTest3;?
? }?
}

//-----------------------------------------------------------------------

<div style="line-height: 22px;">
<span style="line-height: 22px; color: #0000ff;">try</span><span style="line-height: 22px; color: #000000;"><br style="line-height: 22px;">{<br style="line-height: 22px;">..........<br style="line-height: 22px;">.........<br style="line-height: 22px;"></span><span style="line-height: 22px; color: #008000;">//</span><span style="line-height: 22px; color: #008000;">throw</span><span style="line-height: 22px; color: #008000;"><br style="line-height: 22px;"></span><span style="line-height: 22px; color: #000000;">}<br style="line-height: 22px;"></span><span style="line-height: 22px; color: #0000ff;">catch</span><span style="line-height: 22px; color: #000000;"> (</span><span style="line-height: 22px; color: #0000ff;">int</span><span style="line-height: 22px; color: #000000;"> x)<br style="line-height: 22px;">{<br style="line-height: 22px;">.......<br style="line-height: 22px;">}</span>


<dt style="line-height: 22px;">(1)如果在try中没有throw抛出异常 是不是catch 就捕获不到异常啦? throw不可能莫名其妙抛出异常吧 总要判断下吧!<br style="line-height: 22px;">比如if(..)的 这样的话 要这些try catch干什么?多此一举? 直接if语句后面写就的啦!<br style="line-height: 22px;">(2)如果try中没有throw, 哪么catch 会捕获到异常吗?怎么捕获的?这一点很不明白! 如果try中发生异常 哪么到底谁通知catch呢?<br style="line-height: 22px;">(3) throw到底能干什么?</dt>
<dd style="line-height: 22px;">. 如果try里面调用了某个库函数,那个函数throw了异常,就会在这里被catch。这种情况自己就没法判断</dd>
<dt style="line-height: 22px;">throw产生一个异常,这个异常会顺着函数调用的级别逐级向上,由最接近的一个catch来处理。如果一直没有catch,最后就被操作系统捕捉到</dt>
<dd style="line-height: 22px;">1.首先,有的异常的是否抛出不是程序员能控制的,比如内存耗尽,所以需要try...catch,另外,有的时候需要通过抛出异常在程序的其他地方进行 处理,因为当前上下文缺少处理该异常的信息,所以程序员可以自定义异常,并在某种情况下抛出该异常,外层代码需要try...catch来捕获该异常<br style="line-height: 22px;">2.try块里的代码可能没有显示抛出异常,但里面调用的函数有可能抛出异常;怎么捕获的就涉及到异常处理系统的实现,具体的还是由牛人们来解答吧<br style="line-height: 22px;">3.throw就是抛出指定的异常,该异常可以在程序的其他地方被捕获并处理,当然也可能始终没有被捕获,此时,程序一般立刻终止,退出</dd>
<dt style="line-height: 22px;">试想,你写的一个方法method()给别人调用,你知道那个方法执行可能会出错,当出错的时候,你需要把错误信息返回给调用者。这时候,你就只能用throw抛出错误。调用者把对method()的调用放在try块里,就能catch到你抛出的错误,从而获得错误信息。</dt>
<dd style="line-height: 22px;">(1)<br style="line-height: 22px;">???<br style="line-height: 22px;">try的代码段假如没有抛出异常(可能是调用的函数抛出异常),catch确实捕获不到异常;用try catch而不用if能够很快的跳出深层嵌套啊。能够让代码更清晰。<br style="line-height: 22px;"><br style="line-height: 22px;"><br style="line-height: 22px;">(2)<br style="line-height: 22px;"><br style="line-height: 22px;">1里提到了可以捕获深层异常,假如调用的函数中抛出了异常,c++会沿调用链向上回溯(不是通过return回溯),找到第一个try块,<br style="line-height: 22px;">然 后找到对应的catch,假如该异常能被catch处理(类型匹配,其中...处理所有异常),则catch块处理该异常,然后按正常程序继续走下去,回 到正常的函数调用返回链。假如一直找不到一个try,catch块,就会调用C++的“未处理异常捕获器”,这个函数指针是可以设置的,他的默认行为是终 止程序。<br style="line-height: 22px;"><br style="line-height: 22px;">(3) throw的用处是抛出异常,正常的返回用return,而异常用throw。这样程序可以集中处理返回值(这里的返回值不同于C,每个返回值都是正确的,只是含义不同,而C的返回值可能代表着错误),而错误集中在catch块处理,代码逻辑会更清晰明了</dd>

 <div class="clear">
                 
              
              
        
            </div>
</div>

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use