第九章: Error Handling with Exceptions

本文主要介绍Java中的异常处理机制。异常发生时会跳出当前运行环境,将问题交给上一层。异常机制使执行代码和错误处理代码分离,增强可读性和维护性。还介绍了创建自定义异常、异常说明、捕获异常、重抛异常等内容,以及标准Java异常、RuntimeException等类型。

第九章: Error Handling with Exceptions

-- badly formed code will not be run

当发生异常的时侯,它会跳出当前的运行环境,把问题交给上一层运行环境。另外异常机制让程序的执行代码和错误处理代码分离,增强了程序的可读性和维护性。

1、  Basic exceptions

                    if(t == null)

          throw new NullPointerException();

2、Exception arguments

                    throw new NullPointerException("t = null");

3Catching an exception

try {                        //The try block

  // Code that might generate exceptions

} catch(Type1 id1) {        //Exception handlers

  // Handle exceptions of Type1

} catch(Type2 id2) {

  // Handle exceptions of Type2

} catch(Type3 id3) {

  // Handle exceptions of Type3

}

3、 Creating your own exceptions

class MyException extends Exception {

  public MyException() {}

  public MyException(String msg) { super(msg); }

}

4、  The exception specification(异常说明)

                    void f() throws TooBig, TooSmall, DivZero { //...告诉调用你方法的客户程序员,你定义的方法可能抛出哪些异常,因此调用的人就知道编写相应的处理程序来处理潜在的异常,但是你可以撒谎申明你并不真正抛出的异常。

5、  Catching any exception

catch(Exception e) {

  System.err.println("Caught an exception");

}

 

// Demonstrating the Exception Methods.

import com.bruceeckel.simpletest.*;

public class ExceptionMethods {

  private static Test monitor = new Test();

  public static void main(String[] args) {

    try {

      throw new Exception("My Exception");

    } catch(Exception e) {

      System.err.println("Caught Exception");

      System.err.println("getMessage():" + e.getMessage());

      System.err.println("getLocalizedMessage():" +

        e.getLocalizedMessage());

      System.err.println("toString():" + e);

      System.err.println("printStackTrace():");

      e.printStackTrace();

    }

    monitor.expect(new String[] {

      "Caught Exception",

      "getMessage():My Exception",

      "getLocalizedMessage():My Exception",

      "toString():java.lang.Exception: My Exception",

      "printStackTrace():",

      "java.lang.Exception: My Exception",

      "%% /tat ExceptionMethods.main//(.*//)"

    });

  }

} ///:~

6、 Rethrowing an exception

catch(Exception e) {

  System.err.println("An exception was thrown");

  throw e;

// throw e.fillInStackTrace();

}

 

Rethrowing an exception causes it to go to the exception handlers in the next-higher context. Any further catch clauses for the same try block are still ignored. In addition, everything about the exception object is preserved, so the handler at the higher context that catches the specific exception type can extract all the information from that object.

 

you can also do by calling fillInStackTrace( ), which returns a Throwable object that it creates by stuffing the current stack information into the old exception object.

7、  Standard Java exceptions

There are two general types of Throwable objects (“types of” = “inherited from”). Error represents compile-time and system errors that you don’t worry about catching. Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and run-time accidents

8、  RuntimeException

                    --They’re always thrown automatically by Java and you don’t need to include them in your exception specifications.它们会自动得到处理。

9、  Performing cleanup with finally--the finally clause always runs

import com.bruceeckel.simpletest.*;

class ThreeException extends Exception {}

public class FinallyWorks {

  private static Test monitor = new Test();

  static int count = 0;

  public static void main(String[] args) {

    while(true) {

      try {

        // Post-increment is zero first time:

        if(count++ == 0)

          throw new ThreeException();

        System.out.println("No exception");

      } catch(ThreeException e) {

        System.err.println("ThreeException");

      } finally {

        System.err.println("In finally clause");

        if(count == 2) break; // out of "while"

      }

    }

    monitor.expect(new String[] {

      "ThreeException",

      "In finally clause",

      "No exception",

      "In finally clause"

    });

  }

                } ///:~

10、                Exception restrictions(加在异常上的限制)

                    复写方法的时侯,你只能抛出这个方法在基类中声明的异常。(只能申明和抛出不比父类版本中申明的异常多的异常)

11Use exceptions to:

  1. Handle problems at the appropriate level. (Avoid catching exceptions unless you know what to do with them).

  2. Fix the problem and call the method that caused the exception again.

  3. Patch things up and continue without retrying the method.

  4. Calculate some alternative result instead of what the method was supposed to produce.

  5. Do whatever you can in the current context and rethrow the same exception to a higher context.

  6. Do whatever you can in the current context and throw a different exception to a higher context.

  7. Terminate the program.

  8. Simplify. (If your exception scheme makes things more complicated, then it is painful and annoying to use.)

  9. Make your library and program safer. (This is a short-term investment for debugging, and a long-term investment for application robustness.)

 

import requests import logging import socket import time from urllib.parse import urlencode # Disable HTTPS certificate warnings requests.packages.urllib3.disable_warnings() def get_device_logs(server_ip: str = "192.168.137.29", port: int = 21443, mac_address: str = "A1:B2:C3:D4:E5:F6", timeout: int = 15): """ Optimized device log retrieval client with robust error handling """ # 1. Configure URL and headers url = f"https://{server_ip}:{port}/log/file_log_get" headers = { "Device-Mac": mac_address.replace(":", "_"), "Connection": "close" } # 2. Configure detailed logging (English only) logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler()] ) # 3. Network pre-check try: sock = socket.create_connection((server_ip, port), timeout=5) sock.close() logging.info(f"Network path to {server_ip}:{port} is accessible") except socket.error as e: logging.error(f"Network unreachable: {str(e)}") return None MAX_RETRIES = 1 for attempt in range(MAX_RETRIES): try: start_time = time.time() # 4. Optimized request parameters response = requests.get( url, headers=headers, verify=False, timeout=(3, timeout), # Connect timeout 3s, read timeout custom stream=True ) elapsed = time.time() - start_time logging.info(f"HTTP response received! Time: {elapsed:.2f}s, Status: {response.status_code}") if response.status_code == 200: content = bytearray() expected_length = int(response.headers.get('Content-Length', 0)) received_length = 0 try: # 5. Robust chunk handling last_receive_time = time.time() for chunk in response.iter_content(chunk_size=64): current_time = time.time() # 5.1 Chunk timeout detection if current_time - last_receive_time > 10: logging.error("Data reception timeout (10s without chunks)") break if chunk: content.extend(chunk) received_length += len(chunk) last_receive_time = current_time # 5.2 Progress tracking if expected_length > 0: percent = (received_length / expected_length) * 100 logging.info(f"[Progress] {percent:.1f}% ({received_length}/{expected_length} bytes)") else: logging.debug("Received empty keep-alive chunk") # 6. Enhanced error handling except requests.exceptions.ConnectionError as e: logging.error(f"Transfer interrupted: {str(e)}") except requests.exceptions.Timeout: logging.error("Stream transfer timeout!") except requests.exceptions.ChunkedEncodingError as e: logging.error(f"Chunk encoding error: {str(e)}") # 7. Data integrity verification if expected_length > 0 and received_length != expected_length: logging.error(f"Incomplete transfer! Received {received_length}/{expected_length} bytes") elif received_length > 0: logging.info("Data transfer completed successfully") return content.decode('utf-8', errors='replace') else: logging.warning("Received empty response payload") # 8. HTTP error handling logging.error(f"Request failed! Status: {response.status_code}") if response.status_code >= 400: logging.error(f"Response headers: {dict(response.headers)}") # 9. Top-level exception handling except requests.exceptions.SSLError as e: logging.error(f"SSL handshake failed: {str(e)}") except requests.exceptions.ConnectionError: logging.error("Connection failure! Verify: 1) Network connectivity 2) Service status 3) Firewall rules") except requests.exceptions.Timeout: logging.error(f"Global timeout reached ({timeout}s)! Solutions: 1) Check network 2) Increase timeout") except Exception as e: logging.error(f"Unexpected error: {str(e)}") return None def build_debug_url(server_ip: str, port: int, mac: str) -> str: """Generate debug URL with MAC parameter""" params = {"mac": mac.replace(":", "_")} return f"https://{server_ip}:{port}/debug?{urlencode(params)}" if __name__ == "__main__": print("=" * 60) print("Device Log Retrieval Client") print("=" * 60) logs = get_device_logs( server_ip="192.168.137.19", port=21443, mac_address="A1:B2:C3:D4:E5:F6", timeout=20 ) if logs: print("\n" + "=" * 20 + " LOG CONTENT START " + "=" * 20) print(logs[:2000] + ("..." if len(logs)>2000 else "")) print("=" * 20 + " LOG CONTENT END " + "=" * 20) print(f"\nLog retrieval successful! Total length: {len(logs)} characters") debug_url = build_debug_url("192.168.137.19", 21443, "A1:B2:C3:D4:E5:F6") print(f"Debug tip: Visit {debug_url} for server diagnostics") else: print("Log retrieval failed! Review error messages above") print("=" * 60) 增加打印。
10-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值