Chapter 11 Exceptions

本文详细介绍了C++中的异常处理机制,包括如何使用assert进行断言检查、利用signal处理系统级异常、C++异常的基本语法如try-catch块的使用、抛出与捕获异常的方法等。此外还探讨了标准异常的种类及其应用场景,并提供了实用的编程建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

. h
• 11.3 C++ Exceptions
• 11 .4 Throwing
Exceptions
• 11.4.1 Rethrown
Exceptions
• 11 .4.2 Exception
Expressions
• 11.5 Try Blocks
• 11.6 Handlers
• 11 .7 Exception
Specification
• 11.8 terminate()
and
unexpected()
• 11 .9 Example Exception
Code
• 11 .10 Standard
Exceptions and their Uses
• 11.11 Pragmatics
• Summary
• Exercises
Chapter 11 Exceptions
itseraoxhpC1cnp1 • This chapter describes exception handling
in C++. Exceptions
E xc e pt i on s
are generally
unexpected error conditions.
• Assertions
A s e r t i on s
are a program check for
correctness that forces an error exit when it
is violated. One point of view is that an
exception is based on a breakdown of a
contractual guarantee between the provider
of a code, the code's manufacturer, and what
the code is used for, the code's client.
Chapter 11 Exceptions
itseraoxhpC1cnp1 • In this model, the client needs to guarantee
that the conditions for applying the code
exist, and the manufacturer needs to
guarantee that the code will work correctly
under these conditions. In this methodology,
assertions provide the various guarantees.
11.1 Using assert
as s e r t
. h
h
• The user of the computation had the
responsibility of providing correct input.
This was a precondition.
pr e c on di t i on .
• The computation, if successful, satisfied a
postcondition
pos t c on di t i on
.
.
• void assert(bool expression)
e xpr e s i on )
11.1 Using assert
as s e r t
. h
h
• The down side is that the assertion
methodology does not allow a retry or other
repair strategy to continue program
execution.
• Also, assertions do not allow a customized
error message, though it would be easy to
add this capability.
11.2 Using signal.h
s i gn al .• The signal.h
s i gn al . h
file provides a standard
mechanism for handling system-defined
exceptions in a straightforward manner.
• The raise ()
function, prototyped in signal.h
s i gn al . h
,
,
can be used to generate an explicit
exception
11.2 Using signal.h
s i gn al .• sample code
11.2 Using signal.h
s i gn al .• Demo on page 360: signal.cpp
11.2 Using signal.h
s i gn al .
11.2 Using signal.h
s i gn al .
11.2 Using signal.h
s i gn al .• Demo on page 362: vect3.h vect4.h
11.2 Using signal.h
s i gn al .
11.3 C++ Exceptions
• The context for handling an exception is a
try
t r y
block.
• Handlers are declared at the end of a try
block using the keyword catch
c at c h
.
• C++ code can raise an exception in a try
t r y
block by using the throw
t h r ow
expression.
• The exception is handled by invoking an
appropriate handler selected from a list of
handlers found at the end of the handler's
try
t r y
block.
11.3 C++ Exceptions
• Demo on page 364: vect4.h
11 .4 Throwing Exceptions
• throw expression
t h r ow e xpr e s i on
• throw
t h r ow
• The throw
expression
e xpr e s i on
raises an exception.
• The throw
with no argument can be used
inside a catch
to rethrow
r e t h r ow
the current
exception.
• Dem on page 365: throw1.cpp
11 .4 Throwing Exceptions
11 .4 Throwing Exceptions
• Demo on page 366: throw2.cpp
11.4.1 Rethrown Exceptions
• Using throw
without an expression
rethrows
r e t h r ow s
a caught exception.
11 .4.2 Exception Expressions
• Frequently the handlers will not need this
information.
• In this case, it is appropriate to package the
information as an object:
11.5 Try Blocks
11.5 Try Blocks
• Throw Expression Matches the Catch
Handler Type if It Is
ilftIseraydTHnp
– 1. An exact match.
– 2. A
derived type of the public base class
handler type.
– 3. A thrown object type that is convertible to a
pointer type that is the catch
argument.
11.5 Try Blocks
• A t r y
block can be nested.
• If no handler can be found that matches,
then a default behavior is used This is by
default terminate()
(see Section 11.8,
"terminate0 and unexpected()," on page
370).
11.6 Handlers
11 .7 Exception Specification
• Syntactically, an exception specification is
part of a function declaration or function
definition, and has the form:
• function header throw (Type list)
f u n c t i on h e ade r t h r ow ( T y pe l i s t )
11 .7 Exception Specification
• Syntactically, an exception specification is
part of a function declaration or function
definition, and has the form:
• If an exception specification is left off, the
assumption is that an arbitrary exception
can be thrown by such a function.
Violations of these specifications are runtime
errors. They are caught by the function
unexpected().
11.8 terminate()
and unexpected()
• The system-provided function termi nate()
is called when no handler has been provided
to deal with an exception.
• The abort () function is called by default. It
immediately terminates the program,
returning control to the operating system.
• Another action can be specified by using
set-termi nate() to provide a handler.
• These declarations are found in except or
except.h.
11.8 terminate()
and unexpected()
• The system-provided handler unexpected0
is called when a function throws an
exception that was not in its exception
specification list.
• By default, the terminate() function is called.
• Otherwise, a set-unexpected() can be used
to provide a handler.
11 .9 Example Exception Code
• Demo on page 371: vect4.h vect4.cpp
11 .9 Example Exception Code
• Demo on page 371: vect4.h vect4.cpp
11 .9 Example Exception Code
11 .9 Example Exception Code
11 .9 Example Exception Code
11 .10 Standard Exceptions and their
Uses
11 .10 Standard Exceptions and their
Uses
• Standard exceptions are provided by C++
compilers and library vendors.
• Demo on page except.cpp (无库文件及类
型定义)
• A frequent use of standard exceptions is in
testing casts.
• Dem on page 374: bad_cast.cpp (程序需修
改)
11 .10 Standard Exceptions and their
Uses
• A frequent use of standard exceptions is in
testing casts.
11 .10 Standard Exceptions and their
Uses
11 .10 Standard Exceptions and their
Uses
• The standard library exceptions are derived
from the base class exception.
• Two derived classes are logic_error
and
runti
me-error.
• Logic error types include: bad_cast
t_,
out_of_range
agoeronuf
,
and bad-
typeid
iteydp
which are
intended to be
11 .10 Standard Exceptions and their
Uses
• thrown as indicated by their names. The
run-time error types include: range_error
agoern
,
overfl
lfrove
ow_error
oerw
,
and bad_a1 1oc.
.1_• The base class defines a virtual function:
• virtual const
charq
exception: :what()
const throw()
;
• The empty throw specification list indicates
that the function should not itself throw an
exception.
11.11 Pragmatics
• Paradoxically, error recovery is chiefly
concerned with writing correct programs.
• Exception handling is about error recovery.
It is also a transfer-of-control mechanism.
• Error recovery is based on the transfer of
control.
11.11 Pragmatics
• Useful exception handling is the disciplined
recovery when damage occurs.
• In most cases, programming that raises
exceptions should print a diagnostic
message and gracefully terminate.
• What can be agreed upon is that classes can
usefully be provided with error conditions.
• Assertions and simple throws and catches
that terminate the computation are parallel
techniques.
Summary
• 1. Exceptions are generally unexpected
error conditions.
• 2.
The standard library assert.h
as s e r t . h
provides the
macro
assert
(expression)
( e xpr e s i on )
;
• 3.
The signa1.h
s i gn a1. h
file provides a standard
mechanism for handling system-defined
exceptions in a straightforward manner.
Summary
• 4. C++ code can raise an exception by using
the throw
expression.
• 5. Syntactically, throws come in two forms:
throw
throw
expression
e xpr e s i on
Summary
6. Syntactically, a try
block has the form:
try
compound statement
c om pou n d s t at e m e n t
handler list
h an dl e r l i s t
• 7.
Syntactically, a handler has the form:
catch
(formal argument)
( f or m al ar gu m e n t )
compound statement
c om pou n d s t at e m e n t
Summary
• 8. Syntactically, an exception specification
is part of a function declaration, and has the
form:
function header throw (type list)
• 9. The system-provided handler terminate()
is called when no other handler has been
provided to deal with an exception.
compound statement
c om pou n d s t at e m e n 
<think>好的,我现在要解决用户遇到的HTTP 404错误问题,定位URL访问失败的原因。用户提到在使用requests库时出现HTTPError 404 Client Error: Not Found,访问的是localhost的API生成接口。我需要根据提供的引用信息和常见问题来逐步分析可能的原因和解决方案。 首先,用户引用了三个引用。引用[1]提到用户尝试访问默认的ollama地址但服务器找不到,引用[2]是关于POST请求的参数放在请求体中使用curl的例子,引用[3]则是关于curl支持https的问题。不过用户当前的问题是关于404错误的,所以需要聚焦于URL是否正确、服务是否运行、路径是否正确等。 首先,考虑服务是否运行在指定的端口和主机上。用户提到是localhost的API,所以需要确认后端服务是否启动并监听正确的端口。例如,如果服务应该运行在8000端口,那么是否有其他进程占用了该端口,或者服务配置错误监听了其他端口? 接下来,检查请求的URL是否正确。比如,用户是否在URL中正确指定了路径,是否存在拼写错误或缺少必要的路径参数。例如,用户是否将路径/chapter03/request_body/city正确写入代码中?有时候,多一个斜杠或少一个字母都会导致404错误。 然后,查看请求方法是否正确。如果API端点期望的是POST请求,但用户错误地发送了GET请求,也可能导致404。引用[2]中的例子是POST请求,用户需要确认自己的代码是否也使用了正确的HTTP方法。 另外,检查请求头是否正确。比如,是否设置了正确的Content-Type为application/json,这在引用[2]的curl示例中有体现。如果请求头不正确,服务器可能无法正确解析请求体,导致404或其他错误。 还有,请求体是否符合API的要求。用户需要确认发送的JSON数据结构和字段名称是否与API文档一致。虽然这可能更常导致400或422错误,但某些路由配置可能会根据请求体的内容进行路由,从而导致404,尤其是在某些框架中。 另外,考虑服务端路由配置是否正确。例如,在FastAPI或其他框架中,是否正确定义了路由处理程序,并且路径与客户端请求的路径完全匹配。可能存在路由前缀的问题,比如服务端实际路径是/api/v1/chapter03...,而客户端请求缺少了前缀。 此外,网络问题也可能导致404,例如代理设置或防火墙阻止了请求。但因为是localhost环境,这种情况可能性较低,但也不能完全排除。可以尝试使用curl命令测试相同的请求,如引用[2]中的例子,看看是否成功,从而确定是客户端代码问题还是服务端问题。 如果使用curl测试同样出现404,那么问题很可能在服务端配置;如果curl成功而requests代码失败,则需要检查代码中的URL构建、请求方法、头信息和请求体是否正确。用户还可以检查服务端的日志,查看是否收到请求,以及为何返回404,是否有更详细的错误信息。 最后,考虑是否有路径参数或查询参数的问题。例如,某些API可能需要查询参数,而用户可能遗漏了它们,或者路径中有动态参数未正确填充。 总结下来,可能的步骤是: 1. 确认服务正在运行并监听正确端口。 2. 检查请求的URL是否完全正确。 3. 确认HTTP方法(GET、POST等)是否正确。 4. 验证请求头和请求体是否符合API要求。 5. 使用curl测试以排除客户端代码问题。 6. 查看服务端日志以获取更多错误详情。</think>### 逐步解决方案 #### 1. 确认服务运行状态 - 使用命令检查端口占用:`netstat -ano | findstr :8000`(Windows)或`lsof -i :8000`(Linux/Mac) - 重启服务并观察启动日志中的监听地址和端口,例如: ```bash uvicorn main:app --reload --port 8000 --host 0.0.0.0 ``` #### 2. 验证请求URL完整性 - 完整URL示例:`http://localhost:8000/chapter03/request_body/city` - 常见错误案例: - 缺少端口号:`http://localhost/chapter03/...` - 路径拼写错误:`/chapte03/...`(少写r) - 未使用正确协议:服务使用HTTP但请求HTTPS #### 3. 检查HTTP方法与API匹配性 ```python # 错误示例:用GET访问POST接口 response = requests.get("http://localhost:8000/chapter03/request_body/city") # 正确示例:显式指定method参数 response = requests.post( url="http://localhost:8000/chapter03/request_body/city", headers={"Content-Type": "application/json"}, json={"name": "shanghai", "country": "china"} ) ``` #### 4. 调试请求细节(requests库特性) - 启用调试模式查看原始请求: ```python import http.client http.client.HTTPConnection.debuglevel = 1 ``` - 观察输出信息中的`Host`、`Path`、`Method`等关键字段 #### 5. 对比curl命令验证 - 使用与代码等价的curl命令测试(引用[2]示例): ```bash curl -X 'POST' \ 'http://127.0.0.1:8000/chapter03/request_body/city' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "name": "shanghai", "country": "china" }' ``` - 若curl成功而代码失败,说明代码存在参数配置问题 #### 6. 服务端路由诊断 - 检查FastAPI路由定义(示例): ```python # 正确路由定义 @app.post("/chapter03/request_body/city") async def create_city(city: City): return {"message": "created"} # 错误路由案例:路径前缀冲突 app.include_router(router, prefix="/api") # 导致完整路径变为/api/chapter03/... ``` #### 7. 网络层排查 - 关闭客户端防火墙临时测试 - 使用telnet测试端口连通性: ```bash telnet localhost 8000 # 出现空白屏幕表示连接成功 ``` #### 8. 查看服务端访问日志 - 典型日志格式: ```log INFO: 127.0.0.1:58924 - "POST /chapter03/request_body/city HTTP/1.1" 404 Not Found ``` - 根据日志中的`path`信息确认路由是否注册成功 ### 进阶排查工具 1. 使用Wireshark抓包分析HTTP请求 2. 通过Postman构造请求验证参数 3. 在FastAPI中添加中间件打印请求详情: ```python @app.middleware("http") async def log_requests(request: Request, call_next): print(f"Received request: {request.method} {request.url.path}") response = await call_next(request) return response ``` ### 典型错误场景对照表 | 现象 | 可能原因 | 验证方法 | |----------------------|-----------------------------|----------------------------| | 所有端点返回404 | 服务未启动/端口冲突 | 检查进程监听状态 | | 特定端点404 | 1. 路径拼写错误<br>2. 路由未注册 | 对比服务端路由定义 | | curl成功但代码失败 | 1. Headers缺失<br>2. 请求体格式错误 | 启用requests调试模式 | | 间歇性404 | 负载均衡配置错误 | 检查反向代理设置 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值