2016-12-24 67 views

回答

1

檢查此代碼爲用戶定義的異常:

class ShortInputException(Exception): 
    def __init__(self,length,atleast): 
     Exception.__init__(self) 
     self.length = length 
     self.atleast = atleast 

try: 
    text = input('Enter some text: ') 
    if len(text) < 3: 
     raise ShortInputException(len(text),3) 
except EOFError: 
    print('It is end of file.') 
except ShortInputException as ex: 
    print('ShortInputException: You entered {0} length long text. Expected text size is {1}'.format(ex.length,ex.atleast)) 
except KeyboardInterrupt: 
    print('You interrupted the program execution.') 
else: 
    print('No exception/s raised.') 
    print('You entered: {0}'.format(text)) 
1

您可以在類定義的異常或者,也可以在下面創建自己的異常類。

/** * 定義延伸異常 */

類Your_Exception延伸您的異常類異常:

// redefine exception with a message 
public function __construct($message, $code = 0, Exception $previous = null): 

    //Call Parent constructor 
    parent::__construct($message, $code, $previous); 


// custom string representation of object 
public function __to_String(): 
    return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; 


public function user_defined_Function() : 
    echo "user defined exception exception\n"; 
相關問題