捕获异常的Try Catch

如果函数的类型有返回值,那么函数体中的try和catch中都要有返回值,如果有finally则该块中不能有return语句。

因为finally块是必执行的,所以该块在try和catch中return语句前执行

当一个 break、continue 或 goto 语句出现在 finally 块中时,该语句的目标必须在同一 finally 块内,否则会发生编译时错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,使用URLConnection可以创建一个HTTP连接并发送请求。以下是一个使用URLConnection从http传输文件的示例,并在传输过程中捕获异常: ```java import java.io.*; import java.net.*; public class HttpFileUploader { public static void main(String[] args) { String url = "http://example.com/upload"; String fileToUpload = "/path/to/file.jpg"; try { URL fileUrl = new URL(fileToUpload); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setRequestProperty("Content-Disposition", "attachment; filename=\"" + fileUrl.getFile() + "\""); OutputStream out = connection.getOutputStream(); InputStream in = new FileInputStream(new File(fileToUpload)); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } in.close(); out.flush(); out.close(); // Handle response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们使用URLConnection打开一个HTTP连接,并设置请求属性。我们还打开了一个输入流来读取文件,并使用输出流将文件上传到服务器。最后,我们使用一个缓冲读取器来读取服务器的响应。如果在传输文件过程中出现任何异常,就会被try-catch捕获并打印出堆栈跟踪信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值