精华内容
下载资源
问答
  • Python入门进阶篇 No.2 —— try_except基本结构 文章目录Python入门进阶篇 No.2 —— try_except基本结构一、try...一个 except 结构二、try...多个 except 结构总结 前生篇:异常本质_调试核心理念 基础篇:小白...

    Python入门进阶篇 No.2 —— try_except基本结构


    前生篇:异常本质_调试核心理念

    后世篇:try…except…else 结构_try…except…finally 结构

    基础篇:小白不看都能懂 —— Python之真功夫系列(全章)


    一、try…一个 except 结构

    • try…except 是最常见的异常处理结构。结构如下:
    try:
    	被监控的可能引发异常的语句块
    except BaseException [as e]:
    	异常处理语句块
    
    • try 块包含着可能引发异常的代码,except 块则用来捕捉和处理发生的异常。执行的时候,如果 try 块中没有引发异常,则跳过 ecept 块继续执行后续代码;执行的时候,如果 try块中发生了异常,则跳过 try 块中的后续代码,跳到相应的 except 块中处理异常;异常处理完后,继续执行后续代码。
    # 遇到异常的执行顺序:
    # 测试简单的0不能做除数出现的异常
    
    try:
        print('step1')
        a = 6 / 0
        print('step2')
    except BaseException as e:
        print('step3')
        print(e)
    
    print('step4')
    -----------------------
    step1
    step3
    division by zero
    step4
    
    • 我们可以看到,程序执行到引发异常的语句时,直接掉到 except 异常处理语句块进行处理;处理完毕后,继续执行下面的程序。
    # 遇到异常的执行顺序:
    # 测试简单的0不能做除数出现的异常
    
    try:
        print('step1')
        a = 6 / 2
        print('step2')
    except BaseException as e:
        print('step3')
        print(e)
    
    print('step4')
    ----------------------
    step1
    step2
    step4
    
    • try 语句块没有发生异常,则正常执行完 try 块后跳过 except 异常处理语句块,继续往下执行。
    • 循环输入数字,如果不是数字则处理异常;直到输入 66,则结束循环。
    while True:
        try:
            x = int(input('请输入一个数字:'))
            print('输入的数字是', x)
            if x == 66:
                print('退出程序')
                break
        except:
            print('异常:输入的不是一个数字')
    -------------------------------
    输入的数字是 56
    请输入一个数字:xyz
    异常:输入的不是一个数字
    请输入一个数字:66
    输入的数字是 66
    退出程序
    

    二、try…多个 except 结构

    • 上面的结构可以捕获所有的异常,工作中也很常见。但是,从经典理论考虑,一般建议尽量捕获可能出现的多个异常(按照先子类后父类的顺序),并且针对性的写出异常处理代码。为了避免遗漏可能出现的异常,可以在最后增加 BaseException。结构如下:
    try:
    	被监控的、可能引发异常的语句块
    except Exception1:
    	处理 Exception1 的语句块
    except Exception2:
    	处理 Exception2 的语句块
    	
    ... 
    except BaseException:
    	处理可能遗漏的异常的语句块
    
    # 多个except结构
    try:
        a = input('请输入被除数:')
        b = input('请输入除数:')
        c = float(a) / float(b)
        print(c)
    except ZeroDivisionError:
        print('异常,除数不能为0')
    except TypeError:
        print('异常,除数和被除数都应该为数值类型')
    except NameError:
        print('异常,变量不存在')
    except BaseException as  e:
        print(e)
        print(type(e))
    --------------------------------
    请输入被除数:10
    请输入除数:0
    异常,除数不能为0
    

    总结

    以上帮各位总结好了,收藏,关注即可查收。

    前生篇:异常本质_调试核心理念

    后世篇:try…except…else 结构_try…except…finally 结构

    基础篇:小白不看都能懂 —— Python之真功夫系列(全章)


    关注下方公众号,免费拿Python学习资料!!!

    在这里插入图片描述

    展开全文
  • 问题:[单选] 下面那些标签符合(X)HTML的语法结构()A . 国家开放大学 School >B .  哈利波特  Book > C . [body] [/body]D . {book=网页设计}你正在创建一个使用Web部件的ASP.NETWeb站点。你为Web页...

    问题:

    [单选] 下面那些标签符合(X)HTML的语法结构()

    A . 国家开放大学 School >

    B .  哈利波特  Book > 

    C . [body] [/body]

    D . {book=网页设计}

    你正在创建一个使用Web部件的ASP.NETWeb站点。你为Web页增加了一个WebPartZones控件。下面那个控件可以实现给WebPartZones控件增加一个Web部件。() ZoneTemplate。 Control。 WebPartManager。 WebPart。

    根据《公路路基施工技术规范》,不得直接用于路堤填筑的填料是() 膨胀岩石。 易溶性岩石。 重粉质粘土。 盐化岩石。

    Your company has a single active directory domain. All servers run windows server 2008. You install an additional DNS server that runs windows server 2008. You need to delete the pointer record for the IP address 10.3.2.127. what should you do?() Use DNS manager to delete the 127.in-addr.arpa zone.。 Run the dnscmd /recordelte 10.3.2.127 command at the command prompty.。 Run the dnscmd /zonedelete 127.in-addr.apa command at the command prompt.。 Run the dnscmd /recorddelete 10.in-addr.arpa 172.2.3 PRT command at the command prompt.。

    You are modifying a Windows Communication Foundation (WCF) service that allows customers to update financial data. The service currently requires a transaction from the client application and is working correctly. The service contract is defined as follows. (Line numbers are included for reference only.)01 [ServiceContract()]02 public interface IDataUpdate03 {04 [OperationContract()]05 [TransactionFlow(TransactionFlowOption.Mandatory)]06 void Update(string accountNumber, double amount);0708 }0910 public class UpdateService : IDataUpdate11 {1213 [OperationBehavior(TransactionScopeRequired=true, TransactionAutoComplete=true)]14 public void Update(string accountNumber, double amount)15 {16 try17 {18 ...19 }20 catch(Exception ex)21 {22 ...23 }24 }25 }The service must be modified so that client applications do not need to initiate a transaction when calling the operation. The service must use the client application’s transaction if one is available. Otherwise it must use its own transaction.You need to ensure that the service operation is always executed within a transaction.What should you do?() Replace line 05 with the following code. [TransactionFlow(TransactionFlowOption.NotAllowed)]。 Replace line 13 with the following code. [OperationBehavior(TransactionScopeRequired=false, TransactionAutoComplete=true)]。 Replace line 05 with the following code. [TransactionFlow(TransactionFlowOption.Allowed)]。 Replace line 13 with the following code. [OperationBehavior(TransactionScopeRequired=false, TransactionAutoComplete=false)]。

    与公路工程项目施工成本相关的人工费,其费用构成中不包括() 工资性津贴。 生产工人辅助工资。 职工福利费。 住房公积金。

    下面那些标签符合(X)HTML的语法结构()

    参考答案:

    A

    ●  参考解析

    本题暂无解析

    展开全文
  • delphi关于try的正确句法结构 1、句法 var LResult:Variant; //......你在该函数内部需要创建的各类型的实例 try try //......写与这些创建的各类型的实例相关的代码 except on E: ESafecallException do ; ...

    delphi关于try的正确句法结构

    1、句法

    
    var LResult:Variant;
    //......你在该函数内部需要创建的各类型的实例
    try
        try
            //......写与这些创建的各类型的实例相关的代码
        except
            //......进入异常处理:
            on E: ESafecallException do ;         //:比方
            on E: EObjectDisposed do ;            //:比方
            on E: EAccessViolation do ;           //:比方
            on E: EOSError do ;                   //:比方
            on E: EExternalException do ;         //:比方
            on E: EExternal do ;                  //:比方
            else                                  //:比方 
            begin
                //......如果有if或case语句:
                    //......如果有异常返回值,给它赋值LResult:=....;
                    //:彻底释放函数内部创建的引用参照的实例,注意引用参照ARC的类型的释放,具体看该类型的构造函数和解构函数;注意不要误解了“Delphi10.4.2及其后续版本会放弃ARC”的错误提法,其本意是说,原来的处理方式保持不变,$NextGen下一代,新的控件、新的组件、新类型或新的函数,不再在其内部构造ARC的关系啦。若遇TNetHTTPClient的实例的释放,请用MyHTTPClient.DisposeOf;//而不要使用Free;或Destroy;因为你可能将其使用在ARC环境下引用了。 
                    //:若遇TNetHTTPClient的实例的释放:MyHTTPClient.DisposeOf;
            end;
            //......如果有异常返回值,返回:Result:=LResult;
            exit;//:非常重要,不要试图将其留给fanally子句;事实上,当遇到异常except被中断时,是不会退出fanally的,进程始终保持在fanally的输入阶段并不会让fanally进行任何输出;故而exit之前异常处理一定要释放干净,否则即便用户UI交互后内部仍然会有内存泄漏。
        end;
        //......没有遇到异常的其它代码段:
            //......如果有if或case语句:
                //......如果有返回值,给它赋值LResult:=....;
                //......如果有返回值,返回:Result:=LResult;
    finally
        //:彻底释放函数内部创建的各类型的实例;同时注意引用参照ARC的类型的释放,具体看该类型的构造函数和解构函数;注意不要误解了“Delphi10.4.2及其后续版本会放弃ARC”的错误提法,其本意是说,原来的处理方式保持不变,$NextGen下一代,新的控件、新的组件、新类型或新的函数,不再在其内部构造ARC的关系啦。若遇TNetHTTPClient的实例的释放,请用MyHTTPClient.DisposeOf;//而不要使用Free;或Destroy;因为你可能将其使用在ARC环境下引用了。 
        //:若遇TNetHTTPClient的实例的释放:if MyHTTPClient<>nil then MyHTTPClient.DisposeOf;
    
    end;
    
    

    2、运行时刻库基础的except异常类型及中断信号

    //System.SysUtils.pas :
    
    {$IFDEF POSIX}
      TEraRange = record
        StartDate : Integer;         // whole days since 12/31/1899 (TDateTime basis)
        EndDate   : Integer;         // whole days since 12/31/1899 (TDateTime basis)
      end deprecated 'Use EraInfo in TFormatSettings';
    {$ENDIF}
    
    { Exceptions }
    
      PExceptionRecord = System.PExceptionRecord;
    
      Exception = class(TObject)
      private
        FMessage: string;
        FHelpContext: Integer;
        FInnerException: Exception;
        FStackInfo: Pointer;
        FAcquireInnerException: Boolean;
        class constructor Create;
        class destructor Destroy;
      protected
        procedure SetInnerException;
        procedure SetStackInfo(AStackInfo: Pointer);
        function GetStackTrace: string;
        // This virtual function will be called right before this exception is about to be
        // raised. In the case of an external non-Delphi exception, this is called soon after
        // the object is created since the "raise" condition is already in progress.
        procedure RaisingException(P: PExceptionRecord); virtual;
      public
        constructor Create(const Msg: string);
        constructor CreateFmt(const Msg: string; const Args: array of const);
    {$IFNDEF NEXTGEN}
        constructor CreateRes(Ident: NativeUInt); overload;
    {$ENDIF !NEXTGEN}
        constructor CreateRes(ResStringRec: PResStringRec); {$IFNDEF NEXTGEN} overload; {$ENDIF !NEXTGEN}
    {$IFNDEF NEXTGEN}
        constructor CreateResFmt(Ident: NativeUInt; const Args: array of const); overload;
    {$ENDIF !NEXTGEN}
        constructor CreateResFmt(ResStringRec: PResStringRec; const Args: array of const); {$IFNDEF NEXTGEN} overload; {$ENDIF !NEXTGEN}
        constructor CreateHelp(const Msg: string; AHelpContext: Integer);
        constructor CreateFmtHelp(const Msg: string; const Args: array of const;
          AHelpContext: Integer);
    {$IFNDEF NEXTGEN}
        constructor CreateResHelp(Ident: NativeUInt; AHelpContext: Integer); overload;
    {$ENDIF !NEXTGEN}
        constructor CreateResHelp(ResStringRec: PResStringRec; AHelpContext: Integer); {$IFNDEF NEXTGEN} overload; {$ENDIF !NEXTGEN}
        constructor CreateResFmtHelp(ResStringRec: PResStringRec; const Args: array of const;
          AHelpContext: Integer); {$IFNDEF NEXTGEN} overload; {$ENDIF !NEXTGEN}
    {$IFNDEF NEXTGEN}
        constructor CreateResFmtHelp(Ident: NativeUInt; const Args: array of const;
          AHelpContext: Integer); overload;
    {$ENDIF !NEXTGEN}
        destructor Destroy; override;
        function GetBaseException: Exception; virtual;
        function ToString: string; override;
        property BaseException: Exception read GetBaseException;
        property HelpContext: Integer read FHelpContext write FHelpContext;
        property InnerException: Exception read FInnerException;
        property Message: string read FMessage write FMessage;
        property StackTrace: string read GetStackTrace;
        property StackInfo: Pointer read FStackInfo;
      class var
        // Hook this function to return an opaque data structure that contains stack information
        // for the given exception information record. This function will be called when the
        // exception is about to be raised or if this is an external exception such as an
        // Access Violation, called soon after the object is created.
        GetExceptionStackInfoProc: function (P: PExceptionRecord): Pointer;
        // This function is called to return a string representation of the above opaque
        // data structure
        GetStackInfoStringProc: function (Info: Pointer): string;
        // This function is called when the destructor is called to clean up any data associated
        // with the given opaque data structure.
        CleanUpStackInfoProc: procedure (Info: Pointer);
        // Use this function to raise an exception instance from within an exception handler and
        // you want to "acquire" the active exception and chain it to the new exception and preserve
        // the context. This will cause the FInnerException field to get set with the exception
        // in currently in play.
        // You should only call this procedure from within an except block where the this new
        // exception is expected to be handled elsewhere.
        class procedure RaiseOuterException(E: Exception); static;
        // Provide another method that does the same thing as RaiseOuterException, but uses the
        // C++ vernacular of "throw"
        class procedure ThrowOuterException(E: Exception); static;
      end;
    
      EArgumentException = class(Exception);
      EArgumentOutOfRangeException = class(EArgumentException);
      EArgumentNilException = class(EArgumentException);
    
      EPathTooLongException = class(Exception);
      ENotSupportedException = class(Exception);
      EDirectoryNotFoundException = class(Exception);
      EFileNotFoundException = class(Exception);
      EPathNotFoundException = class(Exception);
    
      EListError = class(Exception);
    
      EInvalidOpException = class(Exception);
    
      ENoConstructException = class(Exception);
    
      ExceptClass = class of Exception;
    
      EAbort = class(Exception);
    
      EHeapException = class(Exception)
    {$IFNDEF AUTOREFCOUNT}
      private
        AllowFree: Boolean;
    {$ENDIF}
      protected
        procedure RaisingException(P: PExceptionRecord); override;
      public
    {$IFNDEF AUTOREFCOUNT}
        procedure FreeInstance; override;
    {$ENDIF}
      end;
    
      EOutOfMemory = class(EHeapException);
    
      EInOutError = class(Exception)
      public
        ErrorCode: Integer;
      end;
    
      EExternal = class(Exception)
      public
    {$IFDEF MSWINDOWS}
        ExceptionRecord: PExceptionRecord platform;
    {$ENDIF}
    {$IF defined(LINUX) or defined(MACOS) or defined(ANDROID)}
        ExceptionAddress: LongWord platform;
        AccessAddress: LongWord platform;
        SignalNumber: Integer platform;
    {$ENDIF LINUX or MACOS}
      end;
    
      EExternalException = class(EExternal);
    
      EIntError = class(EExternal);
      EDivByZero = class(EIntError);
      ERangeError = class(EIntError);
      EIntOverflow = class(EIntError);
    
      EMathError = class(EExternal);
      EInvalidOp = class(EMathError);
      EZeroDivide = class(EMathError);
      EOverflow = class(EMathError);
      EUnderflow = class(EMathError);
    
      EInvalidPointer = class(EHeapException);
    
      EInvalidCast = class(Exception);
    
      EConvertError = class(Exception);
    
      EAccessViolation = class(EExternal);
      EPrivilege = class(EExternal);
      EStackOverflow = class(EExternal)
        end deprecated;
      EControlC = class(EExternal);
    {$IF defined(LINUX) or defined(MACOS) or defined(ANDROID)}
      EQuit = class(EExternal) end platform;
    {$ENDIF}
    
    {$IFDEF POSIX}
      ECodesetConversion = class(Exception) end platform;
    {$ENDIF POSIX}
    
      EVariantError = class(Exception);
      EPropReadOnly = class(Exception);
      EPropWriteOnly = class(Exception);
      EAssertionFailed = class(Exception);
      EAbstractError = class(Exception);
      EIntfCastError = class(Exception);
      EInvalidContainer = class(Exception);
      EInvalidInsert = class(Exception);
      EPackageError = class(Exception);
      ECFError = class(Exception);
    
      EOSError = class(Exception)
      public
        ErrorCode: DWORD;
      end;
    
    {$IFDEF MSWINDOWS}
      EWin32Error = class(EOSError)
      end deprecated;
    {$ENDIF}
    
      ESafecallException = class(Exception);
    
      EMonitor = class(Exception);
      EMonitorLockException = class(EMonitor);
      ENoMonitorSupportException = class(EMonitor);
    
      EProgrammerNotFound = class(Exception);
    
      ENotImplemented = class(Exception);
    
      EObjectDisposed = class(Exception);
    
      EOperationCancelled = class(Exception);
    
    {$IFDEF ANDROID}
      EJNIException = class(Exception)
      public
        ExceptionClassName: string;
        constructor CreateWithClassName(const JNIExceptionClassName: string; const Msg: string);
      end;
    {$ENDIF}
    
    {$IF defined(LINUX) or defined(MACOS) or defined(ANDROID)}
    
    {
            Signals
    
        External exceptions, or signals, are, by default, converted to language
        exceptions by the Delphi RTL.  Under Linux, a Delphi application installs
        signal handlers to trap the raw signals, and convert them.  Delphi libraries
        do not install handlers by default.  So if you are implementing a standalone
        library, such as an Apache DSO, and you want to have signals converted to
        language exceptions that you can catch, you must install signal hooks
        manually, using the interfaces that the Delphi RTL provides.
    
        For most libraries, installing signal handlers is pretty
        straightforward.  Call HookSignal(RTL_SIGDEFAULT) at initialization time,
        and UnhookSignal(RTL_SIGNALDEFAULT) at shutdown.  This will install handlers
        for a set of signals that the RTL normally hooks for Delphi applications.
    
        There are some cases where the above initialization will not work properly:
        The proper behaviour for setting up signal handlers is to set
        a signal handler, and then later restore the signal handler to its previous
        state when you clean up.  If you have two libraries lib1 and lib2, and lib1
        installs a signal handler, and then lib2 installs a signal handler, those
        libraries have to uninstall in the proper order if they restore signal
        handlers, or the signal handlers can be left in an inconsistent and
        potentially fatal state.  Not all libraries behave well with respect to
        installing signal handlers.  To hedge against this possibility, and allow
        you to manage signal handlers better in the face of whatever behaviour
        you may find in external libraries, we provide a set of four interfaces to
        allow you to tailor the Delphi signal handler hooking/unhooking in the
        event of an emergency.  These are:
            InquireSignal
            AbandonSignalHandler
            HookSignal
            UnhookSignal
    
        InquireSignal allows you to look at the state of a signal handler, so
        that you can find out if someone grabbed it out from under you.
    
        AbandonSignalHandler tells the RTL never to unhook a particular
        signal handler.  This can be used if you find a case where it would
        be unsafe to return to the previous state of signal handling.  For
        example, if the previous signal handler was installed by a library
        which has since been unloaded.
    
        HookSignal/UnhookSignal setup signal handlers that map certain signals
        into language exceptions.
    
        See additional notes at InquireSignal, et al, below.
    }
    
    const
        RTL_SIGINT          = 0;    // User interrupt (SIGINT)
    {$IFDEF MACOS}
        RTL_SIGQUIT         = 1;    // User interrupt (SIGQUIT)
    {$ENDIF MACOS}
    {$IF Defined(LINUX) or Defined(ANDROID)}
        RTL_SIGFPE          = 1;    // Floating point exception (SIGFPE)
        RTL_SIGSEGV         = 2;    // Segmentation violation (SIGSEGV)
        RTL_SIGILL          = 3;    // Illegal instruction (SIGILL)
        RTL_SIGBUS          = 4;    // Bus error (SIGBUS)
        RTL_SIGQUIT         = 5;    // User interrupt (SIGQUIT)
    {$ENDIF LINUX}
        RTL_SIGLAST         = RTL_SIGQUIT; // Used internally.  Don't use this.
        RTL_SIGDEFAULT      = -1;   // Means all of a set of signals that the we capture
                                    // normally.  This is currently all of the preceding
                                    // signals.  You cannot pass this to InquireSignal.
    
    type
        { TSignalState is the state of a given signal handler, as returned by
          InquireSignal.  See InquireSignal, below.
        }
        TSignalState = (ssNotHooked, ssHooked, ssOverridden);
    
    var
    
      {
        If DeferUserInterrupts is set, we do not raise either SIGINT or SIGQUIT as
        an exception, instead, we set SIGINTIssued or SIGQUITIssued when the
        signal arrives, and swallow the signal where the OS issued it.  This gives
        GUI applications the chance to defer the actual handling of the signal
        until a time when it is safe to do so.
      }
    
      DeferUserInterrupts: Boolean;
      SIGINTIssued: Boolean;
      SIGQUITIssued: Boolean;
    
    {$IF Defined(EXTERNALLINKER)}
      DeferSegmentationViolation: Boolean;
      SIGSEGVIssued: Boolean;
      SIGSEGVFaultInstPtr: NativeUInt;
      SIGSEGVFaultAddrPtr: NativeUInt;
    
    procedure CheckAndClearSIGSEGV;
    {$ENDIF EXTERNALLINKER}
    {$ENDIF LINUX or MACOS or ANDROID}
    
    {$IF Defined(LINUX) or Defined(ANDROID)}
    {$IF Defined(LINUX64) and Defined(CPUX64)}
    function MapFPE(Context: IntPtr; Code:Integer): TRuntimeError;
    {$ELSE}
    function MapFPE(Context: IntPtr): TRuntimeError;
    {$ENDIF}
    
    {$NODEFINE MapFPE}
    function MapFault(Context: IntPtr): TRuntimeError;
    {$NODEFINE MapFault}
    {$ENDIF LINUX or ANDROID}
    
    
    

    展开全文
  • AutoCloseable接口。AutoCloseable接口非常简单,只定义了一...}该接口是JDK 1.7 才新增的一个接口,方法文档注释该方法在try-with-resources语句中会被自动调用,用于自动释放资源。try-with-resources语句是JDK 1...

    AutoCloseable接口。

    AutoCloseable接口非常简单,只定义了一个close方法:

    public interface AutoCloseable {

    void close() Exception;

    }

    该接口是JDK 1.7 才新增的一个接口,方法文档注释该方法在try-with-resources语句中会被自动调用,用于自动释放资源。

    try-with-resources语句是JDK 1.7中一个新的异常处理机制,更方便简洁的关闭在try-catch语句块中使用的资源,这里不得不提及传统的资源释放方式try-catch-finally:

    byte[] b = new byte[1024];

    FileInputStream fis = null;

    try {

    fis = new FileInputStream("my.txt");

    int data = fis.read();

    while(data != -1) {

    data = fis.read(b);

    }

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    } finally {

    if (fis != null) {

    try {

    fis.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    System.out.println(new String(b));

    8b90ca3121e025844d23ef7297176122.png

    传统的资源释放方式是利用finally语句块的特性,不管try语句块里是否抛出异常,finally语句块均会被执行,该方式存在一个较隐蔽的问题,先看下面的改造示例:

    byte[] b = new byte[1024];

    FileInputStream fis = null;

    try {

    fis = new FileInputStream("my.txt");

    int data = fis.read();

    while (data != -1) {

    data = fis.read(b);

    }

    throw new RuntimeException();

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    } catch (Exception e) {

    throw new RuntimeException();

    } finally {

    if (fis != null) {

    try {

    fis.close();

    throw new IOException();

    } catch (IOException e) {

    throw new IOException();

    }

    }

    }

    System.out.println(new String(b));

    02d6a36085ca9ab46e62e328af1823f1.png

    本意是想捕获RuntimeException的,但是因为finally语句块的特性,抛出的IOException“抑制”了RuntimeException,外界捕获到的是IOException,不便于准确的判断问题所在。因为是根据调用栈向外抛出异常。

    如果采用try-with-resources结构:

    byte[] b = new byte[1024];

    try(FileInputStream fis = new FileInputStream("my.txt")) {

    int data = fis.read();

    while (data != -1) {

    data = fis.read(b);

    }

    }

    System.out.println(new String(b));

    ffe4f29f34eee11d7172d7c434dc1800.png

    代码非常简洁,而且FileInputStream资源会被自动关闭,且若抛出异常也是内部的确定异常。

    byte[] b = new byte[1024];

    try (FileInputStream fis = new FileInputStream("my.txt")) {

    int data = fis.read();

    while (data != -1) {

    data = fis.read(b);

    }

    throw new RuntimeException();

    }

    当try-with-resources结构中抛出一个异常,同时fis被释放时也抛出一个异常,最终向外抛出是try-with-resources内部的异常,反而FileInputStream资源释放时的异常被抑制,刚好和try-catch-finally相反

    若在try-with-resources结构中有多个资源需要被释放,只要实现了AutoCloseable接口,均能被自动关闭:

    byte[] b = new byte[1024];

    try(

    FileInputStream fis = new FileInputStream("my.txt");

    BufferedInputStream bis = new BufferedInputStream(fis);

    ) {

    int data = bis.read();

    while (data != -1) {

    data = fis.read(b);

    }

    }

    System.out.println(new String(b));

    关闭的顺序是创建的顺序的逆序。

    Closeable接口继承了AutoCloseable接口,故原有实现Closeable接口的类,均能在try-with-resources结构中使用。

    也可以将自定义的类实现AutoCloseable接口,然后在try-with-resources结构中使用。

    展开全文
  • 词法结构是一套基础性规则,用来描述如何使用javascript来编写程序。与java关系关于javascript有这样一个说法,java和javascript的关系是雷锋和雷锋塔的关系。那到底有没有关系呢javascript最开始的名字是LiveScript...
  • 宜城教育资源网www.ychedu.comtry的用法及短语-try的7种用法-try的短语归纳try的用法1.try可作“审讯”“审理”解,指人的罪过与清白的证实过程,而非结论,也可表示“检验”事物的真伪、价值、强度与效力等。2.try既可...
  • 详解 try 语句

    千次阅读 2021-01-25 09:38:05
    语法结构有两种如下。 有 try 和 except 子句(可多个),以及可选的 else 和 finally 子句: try: suite except expression as identifier: suite else: # 可选 suite finally: # 可选 suite 只有 try 和 ...
  • python3异常处理 try

    2021-01-11 22:11:36
    使用1、异常基础常用结构try:passexcept Exception,ex:pass其他结构try:# 主代码块passexcept KeyError,e:# 异常时,执行该块passelse:# 主代码块执行完,执行该块passfinally:# 无论异常与否,最终...
  • 案例分析一:假定CPU的主频是500MHz。硬盘采用DMA方式进行数据传送,其数据传输率为4MB/s, 每次DMA传输的数据量为8KB, 要求没有任何数据传输被错过。如果CPU在DMA初始化设置和启动硬盘操作等方面用了1000个时钟周期...
  • Python的语法结构十分灵活,也十分简捷,掌握起来也十分迅速。我们可以像写文章一样进行编码,不同的是写文章时使用词、句、段、篇表示层次结构,而python编程使用标识符、命令语句、缩进代码块、模块、类包(库)表示...
  • 1、程序控制结构概述基础程序控制结构有三种,顺序结构、分支结构、循环结构。任何程序都以这三种结构为基础。顺序结构就是程序以单线性顺序从开头至末尾依次执行的结构,中间没有任何的选择分支和循环部分。顺序...
  • 错误处理 try...catch

    2021-07-29 23:28:38
    try…catch语法结构可以捕获错误并可以做更多的事情,而不是直接停止。 try…catch语法 try { // code... } catch (err) { // error handling } 工作流程如下: 1.首先try{…}代码块执行。 2.如果没有错误,...
  • 在原本的try except结构的基础上,Python 异常处理机制还提供了一个 else 块,也就是原有 try except 语句的基础上再添加一个 else 块,即try except else结构。使用 else 包裹的代码,只有当 try 块没有捕获到任何...
  • python 中,引进了很多用来描述和处理异常的类,称为异常类。...try… except 结构try: 被监控的可能引发异常的语句块 except BaseException [as e]: 异常处理语句块 try: 被监控的、可能引发异常的语
  • 在 Python 中,还有另一种异常处理结构,就是 try except else 语句,也就是在原来 try except 语句的基础上再添加一个 else 子句,其作用是指定当 try 块中没有发现异常时要执行的代码。换句话说,当 try 块中发现...
  • 该程序只有一个try和finally块。由于catch块被排除在外,如果遇到异常或任何可丢弃的情况,try块如何工作?它是直接去最后一个街区吗?Try Finally和Try Catch之间的差异可能重复@MP每个人都应该做代码审查,向他们...
  • try/except与其他语言相同,在python中,try/except语句主要是用于throw程序正常执行过程中出现的异常,如语法错(python作为脚本语言没有编译的环节,在执行过程中对语法进行检测,出错后发出异常消息)、数据除零...
  • try - with - resources详解

    2021-07-14 09:41:03
    try-with-resources自JDK7引入,在JDK9中进行了改进,使得用户可以更加方便、简洁的使用try-with-resources。 JDK7之前资源需要手动关闭 下面是一个常见的文件资源关闭的示例: BufferedWriter writer = null; try {...
  • Python 中,finally 语句是与 try 和 except 语句配合使用的,其通常是用来做清理工作的。无论 try 中的语句是否跳入 except 中,最终都要进入 finally 语句,并执行其中的代码块。有些时候,程序在 try 块里打开了...
  • Python 提供了try except语句捕获并处理异常,该异常处理语句的基本语法结构如下:try:可能产生异常的代码块except [(Error1, Error2, ...) [as e]]:处理异常的代码块1except [(Error3, Error4, ...) [as e]]:处理...
  • try...excpt的使用2.1 语法介绍2.2 执行流程2.3 异常类型的查看3. try...except...else4. try...except...finally 1. 什么是异常 在执行python程序时,会有出现错误的可能。导致出错的原因有一般两种: 语法错误:...
  • 同样主人公阿愚喜欢上C++中异常处理后,当然也首先关注它的游戏规则,这就是C++中异常处理的语法。关键字1、try2、catch3、throw其中关键字try表示定义一个受到监控、受到保护的程序代码块;关键字catch与try...
  • (try finally)Python try except异常处理详解python标准异常异常名称描述BaseException所有异常的基类SystemExit解释器请求退出KeyboardInterrupt用户中断执行(通常是输入^C)Exception常规错误的基类StopIteration...
  • (注:一定要先抛才能获取)需要进行异常处理的代码都必须放入 try 代码块内,以便捕获可能存在的异常。每一个 try 至少要有一个与之对应的 catch。使用多个 catch可以捕获不同的类所产生的异常。当 try 代码块不再抛...
  • try()...catch()的用法

    2021-04-06 16:37:10
    在stackoverflow偶尔看到的一个关于try()...catch()的用法,通常我们使用try...catch()捕获异常的,如果遇到类似IO流的处理,要在finally部分关闭IO流,当然这个是JDK1.7之前的写法了;在JDK7优化后的try-with-...
  • C++ try……catch catch(CException *e) 打印异常信息 不经意间的内存泄露:try-catch(CException *e) [异常对象需要手动释放] C++ try catch 捕获空指针异常,数组越界异常 C++ try catch 异常类 异常类大全 C...
  • 在看android的SystemServer.java 由于不懂JAVA,所以看一点记录一点。本文主要是针对JAVA的异常处理的一些语句进行...try { [tryStatements]}catch(exception){ [catchStatements]}finally { [finallyStatements]}...
  • Python 基础语法

    2021-01-30 01:15:37
    'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] 1 2 3 importkeyword ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 111,881
精华内容 44,752
关键字:

try的语法结构