在程序运行中,可能会遇到各种预期之外的情况,如用户输入错误、网络故障、硬件问题等。通过异常处理机制,将错误处理代码与正常的业务逻辑代码分离开来,程序可以在遇到这些问题时做出适当的响应,而不是直接崩溃,这样可以显著提高程序的稳定性和可靠性,使得代码更加清晰、易于阅读和维护。julia语言通常使用 try-catch 、error()、throw()、finally 这几种方式来进行异常处理。
try-catch方法
格式:try...
catch...
end
尝试计算-4的平方根,但是负数没法算平方根,所以输出异常处理
try sqrt(-4)
catchprintln("负数无法求平方根")
end
根据输入键盘数字求平方根,因为需要读取键盘输入数值,代码需要在julia终端输入 julia xxx.jl 运行
println("输入一个数: ")
myx = readline()
x = parse(Int, myx)tryprintln("输入的是: ", x, "平方根为:", sqrt(x))
catchprintln("输入的是: ", x, "平方根不能为负数")
end
finally
无论try
块中的代码是否成功执行,或者catch
块是否捕获到了异常,finally
块中的代码总是会被执行。
格式:
try...
catch...
finally...
end
根据用户输入的文件名字打开文件,如果找不到该文件就创建一个文件并在里面输入文字
println("输入打开的文件名: ")
mystr = readline()trymyf = open(mystr, "r")str = readlines(myf)println(str)catchprintln("文件名不存在")finally open("GGboy.txt", "w") do io write(io, "吔屎了你")endend
运行结果
error()
function another_function(y) if y == 0 error("扑街啦,死靓仔!") end return 10 / y
end try result = another_function(0)
catch e println("Caught an error: $e")
end
如果将 result = another_function() 中的值改为其他数字时,会在终端打印数字。
throw()
struct MyCustomException <: Exception message::String
end # 使用 throw()抛出自定义异常的函数
function my_function(x) if x < 0 throw(MyCustomException("thank you jesus")) end return 2 * x
end try result = my_function(-5)
catch e if e isa MyCustomException println("Caught a custom exception: $(e.message)") else println("Caught an unexpected exception: $e") end
end
整活(使用HTTP包下载网页源码及图片)
using HTTP function download_file(url::String, filename::String) try # 发送HTTP.get请求获取数据 response = HTTP.get(url) # 检查响应是否成功 if response.status == 200 # 写入文件 open(filename, "w") do file write(file, response.body) end println("靓仔你成功下载了: $(filename)") else println("你失败了吊毛, 状态码: $(response.status)") end catch e # 捕获异常并处理 println("凉了,铁子: $(e)") end
end html_url = "http://www.baidu.com"
html_filename = "GG爆.html"
download_file(html_url, html_filename) image_url = "https://c-ssl.duitang.com/uploads/blog/202304/22/20230422153706_c4c2c.jpeg"
image_filename = "GGBOND.jpg"
download_file(image_url, image_filename)
运行结果