Python은 예외 객체를 사용하여 비정상적인 상황을 나타냅니다. 오류가 발생하면 예외가 발생합니다. 예외 객체가 처리되거나 포착되지 않으면 프로그램은 소위 트레이스백(오류 메시지)을 사용하여 실행을 종료합니다.
>>> 1/0
트레이스백( 가장 최근 호출 마지막):
파일 "
1/0
ZeroDivisionError: 정수 나누기 또는 0으로 모듈로
raise 문
예외를 발생시키려면 클래스(Exception의 하위 클래스) 또는 인스턴스 매개변수 번호를 사용하여 raise 문을 호출할 수 있습니다. 다음 예에서는 내장된 예외 클래스를 사용합니다.
>>> raise Exception #引发一个没有任何错误信息的普通异常 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise Exception Exception >>> raise Exception('hyperdrive overload') # 添加了一些异常错误信息 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> raise Exception('hyperdrive overload') Exception: hyperdrive overload
시스템과 함께 제공되는 내장 예외 클래스:
>>> 예외 가져오기
>>> dir(예외)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', ' DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError' , 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', ' StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning' , 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
와! 일반적으로 사용되는 내장 예외 클래스는 다음과 같습니다.
사용자 정의 예외
내장 예외 클래스가 대부분의 상황을 다루고 많은 요구 사항에 충분하지만 때로는 직접 생성해야 하는 경우도 있습니다. 예외 클래스.
다른 일반 클래스와 동일합니다. 직접 또는 간접적으로 Exception 클래스에서 상속되는지 확인하세요. 다음과 같습니다.
>>> class someCustomExcetion(Exception):pass
물론 이 클래스에 몇 가지 메서드를 추가할 수도 있습니다.
예외 포착
try/Exception을 사용하여 예외 포착 및 처리를 구현할 수 있습니다.
사용자가 두 개의 숫자를 입력한 후 나누는 프로그램을 만든다고 가정해 보겠습니다.
x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y #运行并且输入 Enter the first number: 10 Enter the second number: 0 Traceback (most recent call last): File "I:/Python27/yichang", line 3, in <module> print x/y ZeroDivisionError: integer division or modulo by zero 为了捕捉异常并做出一些错误处理,可以这样写: try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #再来运行 >>> Enter the first number: 10 Enter the second number: 0
입력한 숫자는 다음과 같습니다. 0! #어때요? 이번에는 훨씬 더 친숙해졌습니다
사용자와 상호 작용하는 동안 사용자가 예외 정보를 볼 수 없도록 하려면 디버깅 중에 예외를 발생시키는 것이 좋습니다. "차단" 메커니즘을 어떻게 켜고/끄나요?
class MuffledCalulator: muffled = False #这里默认关闭屏蔽 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Divsion by zero is illagal' else: raise #运行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0') Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了 >>> calculator.muffled = True #现在打开屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal
여러 절 제외
위를 실행하면(숫자 2개 입력 , 찾기 Division) 프로그램에 표면의 내용을 입력하면 또 다른 예외가 발생합니다:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #运行输入: >>> Enter the first number: 10 Enter the second number: 'hello.word' #输入非数字 Traceback (most recent call last): File "I:\Python27\yichang", line 4, in <module> print x/y TypeError: unsupported operand type(s) for /: 'int' and 'str' #又报出了别的异常信息
좋아요! 이 상황을 처리하기 위해 예외 처리기를 추가할 수 있습니다.
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" except TypeError: # 对字符的异常处理 print "请输入数字!" #再来运行: >>> Enter the first number: 10 Enter the second number: 'hello,word'
숫자를 입력하세요!
한 블록으로 여러 예외 포착
물론 한 블록을 사용하여 여러 예외를 포착할 수도 있습니다.
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except (ZeroDivisionError,TypeError,NameError): print "你的数字不对!
"
모든 예외 잡기
위 프로그램처럼 프로그램이 여러 예외를 처리하더라도 실행 후 아래와 같은 내용을 입력하면
>>> Enter the first number: 10 Enter the second number: #不输入任何内容,回车 Traceback (most recent call last): File "I:\Python27\yichang", line 3, in <module> y = input('Enter the second number: ') File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing
실수로 무시하는 상황이 항상 있습니다. 모든 예외를 포착하기 위해 코드를 사용하려면 Ignore를 제외하고 사용할 수 있습니다. 절의 모든 예외 클래스:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except: print '有错误发生了!' #再来输入一些内容看看 >>> Enter the first number: 'hello' * )0
오류가 발생했습니다.
끝
걱정하지 마세요! 마지막 상황에 대해 이야기해 보겠습니다. 사용자가 실수로 잘못된 정보를 입력했습니다. 다시 입력할 수 있는 기회를 줄 수 있나요? 패배 시 종료되도록 루프를 추가할 수 있습니다.
while True: try: x = input('Enter the first number: ') y = input('Enter the second number: ') value = x/y print 'x/y is',value except: print '列效输入,再来一次!' #运行 >>> Enter the first number: 10 Enter the second number: 列效输入,再来一次! Enter the first number: 10 Enter the second number: 'hello' 列效输入,再来一次! Enter the first number: 10 Enter the second number: 2 x/y is 5

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.

"for"and "while"loopsare : 1) "에 대한"loopsareIdealforitertatingOverSorkNowniterations, whide2) "weekepindiTeRations.Un

Python에서는 다양한 방법을 통해 목록을 연결하고 중복 요소를 관리 할 수 있습니다. 1) 연산자를 사용하거나 ()을 사용하여 모든 중복 요소를 유지합니다. 2) 세트로 변환 한 다음 모든 중복 요소를 제거하기 위해 목록으로 돌아가지 만 원래 순서는 손실됩니다. 3) 루프 또는 목록 이해를 사용하여 세트를 결합하여 중복 요소를 제거하고 원래 순서를 유지하십시오.

fastestestestedforListCancatenationInpythondSpendsonListsize : 1) Forsmalllist, OperatoriseFficient.2) ForlargerLists, list.extend () OrlistComprehensionIsfaster, withextend () morememory-efficientBymodingListsin-splace.

toInsertElmentsIntoapyThonList, useAppend () toaddtotheend, insert () foraspecificposition, andextend () andextend () formultipleElements.1) useappend () foraddingsingleitemstotheend.2) useinsert () toaddatespecificindex, 그러나)

pythonlistsareimplementedesdynamicarrays, notlinkedlists.1) thearestoredIntIguousUousUousUousUousUousUousUousUousUousInSeripendExeDaccess, LeadingSpyTHOCESS, ImpactingEperformance

PythonoffersfourmainmethodstoremoveElementsfromalist : 1) 제거 (값) 제거 (값) removesthefirstoccurrencefavalue, 2) pop (index) 제거 elementatAspecifiedIndex, 3) delstatemeveselementsByindexorSlice, 4) RemovesAllestemsfromTheChmetho

Toresolvea "permissionDenied"오류가 발생할 때 오류가 발생합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Dreamweaver Mac版
시각적 웹 개발 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기