nim语言的try...except流程居然没有python那样的else分支

本文探讨了使用Nim语言进行网络请求时遇到的奇怪问题:在一个try-finally结构中,变量resp在finally块中无法被识别。文章深入分析了代码片段,包括HTTP请求的构造、响应处理以及异常捕获机制。

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

nim c -d:ssl -r test.nim

import httpclient, streams, cookies
import system
import typetraits

const UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"


var client = newHttpClient(userAgent = UserAgent)

var url:string
url = "https://www.baidu.com"

var headers = newHttpHeaders({"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" })
#var resp:Response

try:
    let resp = client.request(url, headers=headers)
    echo resp.repr[..200]
except Exception as exc:
    echo(exc.repr)
finally:
    echo resp.repr
    echo resp.code
    if resp.code.is4xx or resp.code.is5xx:
        raise newException(HttpRequestError, resp.status)
    else:
        echo resp.bodyStream.readAll()
        echo resp.status
        echo resp.headers

以上代码的奇怪之处就在于, 22行的resp居然没有定义, 也就是说, try: 后面的代码块里, 使用let定义了一个resp, 但是到了finally那里, 编译器就不认识了.

 

当然, 也没有python里的else分支,让人觉得很无助.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值