Что такое ошибка во время выполнения?
Я сделал игру с Python 2.6. Я также превратил его в исполняемый файл с помощью cx_Freeze 4.3. Когда я запустил исполняемый файл на моем компьютере, он получил это:
Microsoft Visual C++ Runtime Library
Program: C:\Users\smm\Desktop\asteroid shower 1.4.5\asteroid.exe
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Я не понимаю, что здесь произошло. Я пытался решить проблему, но безуспешно. Затем я искал ошибку времени выполнения в Google, и он сказал, что это может быть совместимость. Я написал оригинальный скрипт для Windows Vista с загруженной версией Windows 7 Python 2.6. Я сделал это, потому что в Windows Vista не было интернета, поэтому я загрузил файлы python, pygame и cx_freeze .msi на свой ноутбук с Windows 7. Затем я перенес файлы на рабочий стол Windows Vista. Это проблема? Или, может быть, сценарий? Я не думаю, что это сценарий, так как я могу играть в игру, когда это все еще сценарий Python. Это немного долго, хотя... Я использую Windows 7 с Python 2.6, Pygame 2.6 и cx_freeze 4.3. Спасибо, если вы можете мне помочь:).
# By Sandy Goetjens
# Asteroid Shower V1.4.5
import pygame, random, sys, time
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
TEXTCOLOR = WHITE
BACKGROUNDCOLOR = BLACK
FPS = 40
ASTEROIDCIRCLESPEED = 1
ASTEROIDMINSIZE = 10
ASTEROIDMAXSIZE = 40
ASTEROIDMINSPEED = 1
ASTEROIDMAXSPEED = 8
ADDNEWASTEROIDRATE = 10
PLAYERMOVERATE = 5
TOKENSIZE = 20
TOKENSPEED = 8
ADDNEWTOKENRATE = 6
BULLETSPEED = 3
BULLETFIRETIME = 1000
BULLETSIZE = 20
GHOSTSIZE = 20
GHOSTSPEED = 5
ADDNEWGHOSTRATE = 8
HEALTHSIZE = 20
HEALTHSPEED = 10
ADDNEWHEALTHRATE = 9
EYEBALLSIZE = 20
EYEBALLSPEED = 15
ADDNEWARROWRATE = 5
ARROWSIZE = 10
ARROWSPEED = 18
ADDNEWDUSTRATE = 8
DUSTSIZE = 12
DUSTSPEED = 16
ADDNEWEYEBALLRATE = 10
GHOSTSIZE = 20
GHOSTSPEED = 10
ADDNEWGHOSTRATE = 15
NEWASTEROIDSPEED = 30
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitHealth(playerRect, healths):
for h in healths:
if playerRect.colliderect(h['rect']):
return True
return False
def drawAsteroidRotation(ASTEROIDCIRCLESPEED, rotation, asteroids):
for a in asteroids:
left = leftCordinOfAsteroid
pygame.draw.rect(windowSurface, WHITE, (left, ASTEROIDSIZE, ASTEROIDSIZE))
pygame.display.update()
def asteroidAnimation(asteroids):
for rotation in asteroids(ASTEROIDCIRCLESPEED):
drawAsteroidRotation(ASTEROIDCIRCLESPEED, rotation, asteroids)
def bulletHasHitAsteroid(bulletRect, asteroids):
for b in bullets:
if bulletRect.colliderect(b['rect']):
bombExplosion.play()
return True
bombExplosion.stop()
return False
def playerHasHitToken(playerRect, tokens):
for t in tokens:
if playerRect.colliderect(t['rect']):
return True
return False
def playerHasHitBaddie(playerRect, asteroids):
for a in asteroids:
if playerRect.colliderect(a['rect']):
return True
return False
def playerHasHitGhost(playerRect, ghosts):
for g in ghosts:
if playerRect.colliderect(g['rect']):
return True
return False
def playerHasHitEyeball(playerRect, eyeballs):
for e in eyeballs:
if playerRect.colliderect(e['rect']):
return True
return False
def playerHasHitArrow(playerRect, arrows):
for r in arrows:
if playerRect.colliderect(r['rect']):
return True
return False
def playerHasHitDust(playerRect, dusts):
for d in dusts:
if playerRect.colliderect(d['rect']):
return True
return False
def asteroidHasHitBullet(baddieRect, bullets):
for a in asteroids:
if asteroidRect.collierect(a['rect']):
return True
return False
def drawText(text, font, surface, x, y):
font = pygame.font.Font(None, 48)
textobj = font.render(text, 10, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
def version(font, windowSurface, versionbackgroundImage):
while True:
windowSurface.blit(versionBackgroundImage, (0, 0))
drawText('Buy the full game to play more', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 200)
drawText('levels!! Plus bonus', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 150)
drawText('updates and new game', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 100)
drawText('releases!! Presented', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 50)
drawText('by Desert Labotories', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 0)
pygame.display.update()
waitForPlayerToPressKey()
return
def Credits(font, windowSurface, creditbackgroundImage):
while True:
windowSurface.blit(creditBackgroundImage, (0, 0))
drawText('Created by Sandy Goetjens', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 50)
drawText('Presented by Desert Labortories', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 100)
pygame.display.update()
waitForPlayerToPressKey()
return
def waitForPlayerToEnterKeys():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escapes quits
terminate()
if event.key == K_c:
Credits(font, windowSurface, creditBackgroundImage)
if event.key == K_x:
version(font, windowSurface, versionBackgroundImage)
return
def Level3(font, windowSurface, level):
while True:
drawText('Buy the full version to', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3))
drawText('continue playing!', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 50)
drawText('8 new and challenging levels!', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3 + 100))
pygame.display.update()
waitForPlayerToPressKey()
return
def Level1(font, windowSurface, level, applauseSound):
while True:
applauseSound.play()
drawText('LEVEL 1 completed!', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3))
drawText('Press a key to continue.', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 50)
drawText('By Sandy Goetjens.', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 150)
drawText('RATE US ON FACEBOOK', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 200)
drawText('Entering BLUE LANDS', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 250)
pygame.display.update()
applauseSound.stop()
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
if True:
level = 2
kilometres = 3000
return
# set up pygame, the window, and the mouse cursor
pygame.init()
global level, kilometres
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_icon(pygame.image.load('asteroid.icon'))
pygame.display.set_caption('Asteroid Shower Demo V1.4.5')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
bombExplosion = pygame.mixer.Sound('explosion-01.wav')
warnSound = pygame.mixer.Sound('alarm02.wav')
applauseSound = pygame.mixer.Sound('applause2.wav')
# set up images
playerImage = pygame.image.load('player.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('asteroid.png')
baddieRect = baddieImage.get_rect()
tokenImage = pygame.image.load('tokens.png')
bulletImage = pygame.image.load('bullet.png')
bulletRect = bulletImage.get_rect()
ghostImage = pygame.image.load('ghosts.png')
healthImage = pygame.image.load('health.png')
eyeballImage = pygame.image.load('eyeball.png')
arrowImage = pygame.image.load('arrow.png')
dustImage = pygame.image.load('dust.png')
versionBackgroundImage = pygame.image.load('background.png')
creditBackgroundImage = pygame.image.load('creditsbackground.png')
creditsPage = pygame.image.load('credits.png')
desertLabs = pygame.image.load('desert labs.png')
# show the "Start" screen
windowSurface.blit(creditsPage, (0, 0))
pygame.time.wait(1000)
drawText('Asteroid Shower ', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 4 - 100))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 4 - 50))
pygame.display.update()
waitForPlayerToEnterKeys()
level = 0
bullet = 50
token = 0
topScore = 0
while True:
# set up the start of the game
tokens = []
asteroids = []
bullets = []
eyeballs = []
arrows = []
dusts = []
ghosts = []
healths = []
score = 0
health = 100
kilometres = 2500
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
asteroidAddCounter = 0
ghostAddCounter = 0
tokenAddCounter = 0
healthAddCounter = 0
eyeballAddCounter = 0
arrowAddCounter = 0
dustAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop runs while the game part is playing
score += 1 # increase score
kilometres -= 1 # decrease kilomteres
if level == 0:
if kilometres == 0:
level = 2
kilometres = 3000
Level1(font, windowSurface, level, applauseSound)
# Go to level 3 title
if level == 2 and kilometres == 0:
Level3(font, windowSurface, level)
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.key == K_z:
if token > 500:
token -= 500
if bullet < 200:
bullet += 50
if event.key == K_x:
if token > 600:
token -= 600
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
if token > 0:
if event.type == MOUSEBUTTONUP:
# If player clicks mouse bullets will fire
if bullet > 0:
bullet -= 1
newBullet = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-BULLETSIZE), 0 - BULLETSIZE, BULLETSIZE, BULLETSIZE),
'speed': (BULLETSPEED),
'surface':pygame.transform.scale(bulletImage, (BULLETSIZE, BULLETSIZE)),
}
bullets.append(newBullet)
# Add new tokens at the top of the screen, if needed
if not reverseCheat and not slowCheat:
tokenAddCounter += 1
if tokenAddCounter == ADDNEWTOKENRATE:
tokenAddCounter = 0
newToken = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-TOKENSIZE), 0 - TOKENSIZE, TOKENSIZE, TOKENSIZE),
'speed': (TOKENSPEED),
'surface':pygame.transform.scale(tokenImage, (TOKENSIZE, TOKENSIZE)),
}
tokens.append(newToken)
if level == 0:
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
asteroidAddCounter += 1
if asteroidAddCounter == ADDNEWASTEROIDRATE:
asteroidAddCounter = 0
asteroidSize = random.randint(ASTEROIDMINSIZE, ASTEROIDMAXSIZE)
newAsteroid = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-asteroidSize), 0 - asteroidSize, asteroidSize, asteroidSize),
'speed': random.randint(ASTEROIDMINSPEED, ASTEROIDMAXSPEED),
'surface':pygame.transform.scale(baddieImage, (asteroidSize, asteroidSize)),
}
asteroids.append(newAsteroid)
if level == 0:
if not reverseCheat and not slowCheat:
ghostAddCounter += 1
if ghostAddCounter == ADDNEWGHOSTRATE:
ghostAddCounter = 0
newGhost = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-GHOSTSIZE), 0 - GHOSTSIZE, GHOSTSIZE, GHOSTSIZE),
'speed': (GHOSTSPEED),
'surface': pygame.transform.scale(ghostImage, (GHOSTSIZE, GHOSTSIZE)),
}
ghosts.append(newGhost)
if health < 50:
if not reverseCheat and not slowCheat:
healthAddCounter += 1
if healthAddCounter == ADDNEWHEALTHRATE:
healthAddCounter = 0
newHealth = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-HEALTHSIZE), 0 - HEALTHSIZE, HEALTHSIZE, HEALTHSIZE),
'speed': (HEALTHSPEED),
'surface': pygame.transform.scale(healthImage, (HEALTHSIZE, HEALTHSIZE)),
}
healths.append(newHealth)
if level == 2:
if not reverseCheat and not slowCheat:
eyeballAddCounter += 1
if eyeballAddCounter == ADDNEWEYEBALLRATE:
eyeballAddCounter = 0
newEyeball = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-EYEBALLSIZE), 0 - EYEBALLSIZE, EYEBALLSIZE, EYEBALLSIZE),
'speed': (EYEBALLSPEED),
'surface': pygame.transform.scale(eyeballImage, (EYEBALLSIZE, EYEBALLSIZE)),
}
eyeballs.append(newEyeball)
if level == 2:
if not reverseCheat and not slowCheat:
arrowAddCounter += 1
if arrowAddCounter == ADDNEWARROWRATE:
arrowAddCounter = 0
newArrow = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-ARROWSIZE), 0 - ARROWSIZE, ARROWSIZE, ARROWSIZE),
'speed': (ARROWSPEED),
'surface': pygame.transform.scale(arrowImage, (ARROWSIZE, ARROWSIZE)),
}
arrows.append(newArrow)
if level == 2:
if not reverseCheat and not slowCheat:
dustAddCounter += 1
if dustAddCounter == ADDNEWDUSTRATE:
dustAddCounter = 0
newDust = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-DUSTSIZE), 0 - DUSTSIZE, DUSTSIZE, DUSTSIZE),
'speed': (DUSTSPEED),
'surface': pygame.transform.scale(dustImage, (DUSTSIZE, DUSTSIZE)),
}
dusts.append(newDust)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
# Move the baddies down.
for a in asteroids:
if not reverseCheat and not slowCheat:
a['rect'].move_ip(0, a['speed'])
elif reverseCheat:
a['rect'].move_ip(0, -5)
elif slowCheat:
a['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for a in asteroids[:]:
if a['rect'].top > WINDOWHEIGHT:
asteroids.remove(a)
for g in ghosts:
if not reverseCheat and not slowCheat:
g['rect'].move_ip(0, g['speed'])
elif reverseCheat:
g['rect'].move_ip(0, -5)
elif slowCheat:
g['rect'].move_ip(0, 1)
# Delete each ghost that have fallen past the bottom
for g in ghosts[:]:
if g['rect'].top > WINDOWHEIGHT:
ghosts.remove(g)
# Move the tokens down
for t in tokens:
if not reverseCheat and not slowCheat:
t['rect'].move_ip(0, t['speed'])
elif reverseCheat:
t['rect'].move_ip(0, -5)
elif slowCheat:
t['rect'].move_ip(0, 1)
# Delete each token that have fallen past the bottom
for t in tokens[:]:
if t['rect'].top > WINDOWHEIGHT:
tokens.remove(t)
# Move bullets down
for b in bullets:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in bullets[:]:
if b['rect'].top > WINDOWHEIGHT:
bullets.remove(b)
# Move health down
for h in healths:
if not reverseCheat and not slowCheat:
h['rect'].move_ip(0, h['speed'])
elif reverseCheat:
h['rect'].move_ip(0, -5)
elif slowCheat:
h['rect'].move_ip(0, -1)
for h in healths[:]:
if h['rect'].top > WINDOWHEIGHT:
healths.remove(h)
# Move eyeballs down
for e in eyeballs:
if not reverseCheat and not slowCheat:
e['rect'].move_ip(0, e['speed'])
elif reverseCheat:
e['rect'].move_ip(0, -5)
elif slowCheat:
e['rect'].move_ip(0, -1)
for e in eyeballs[:]:
if e['rect'].top > WINDOWHEIGHT:
eyeballs.remove(e)
for r in arrows:
if not reverseCheat and not slowCheat:
r['rect'].move_ip(0, r['speed'])
elif reverseCheat:
r['rect'].move_ip(0, -5)
elif slowCheat:
r['rect'].move_ip(0, -1)
for r in arrows[:]:
if r['rect'].top > WINDOWHEIGHT:
arrows.remove(r)
for d in dusts:
if not reverseCheat and not slowCheat:
d['rect'].move_ip(0, d['speed'])
elif reverseCheat:
d['rect'].move_ip(0, -5)
elif slowCheat:
d['rect'].move_ip(0, -1)
for d in dusts[:]:
if d['rect'].top > WINDOWHEIGHT:
dusts.remove(d)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
if level == 2:
windowSurface.fill(BLUE)
# Draw the score top score, token, how many bombs, health and how much boss life
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
drawText('Token: %s' % (token), font, windowSurface, 10, 80)
drawText('Bombs: %s' % (bullet), font, windowSurface, 10, 120)
drawText('Km: %s' % (kilometres), font, windowSurface, 10, 160)
drawText('Health: %s' % (health), font, windowSurface, 10, 560)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Check the score to enter the next level
# Draw each asteroid
for a in asteroids:
windowSurface.blit(a['surface'], a['rect'])
for g in ghosts:
windowSurface.blit(g['surface'], g['rect'])
# Draw each token
for t in tokens:
windowSurface.blit(t['surface'], t['rect'])
# Draw each bullet
for b in bullets:
windowSurface.blit(b['surface'], b['rect'])
# Draw each health
for h in healths:
windowSurface.blit(h['surface'], h['rect'])
# Draw each eyeball
for e in eyeballs:
windowSurface.blit(e['surface'], e['rect'])
# Draw each arrow
for r in arrows:
windowSurface.blit(r['surface'], r['rect'])
# Draw each dust
for d in dusts:
windowSurface.blit(d['surface'], d['rect'])
pygame.display.update()
# Check if any of the health have hit the player
if playerHasHitHealth(playerRect, healths):
health += 5
if health < 100:
health -= 0
healths.remove(h)
# Cheack if any of the eyeballs have hit the player
if playerHasHitEyeball(playerRect, eyeballs):
health -= 10
if health == 0:
if score > topScore:
topScore = score
break
# Check if any of the arrows have hit the player
if playerHasHitArrow(playerRect, arrows):
health -= 15
if health == 0:
if score > topScore:
topScore = score
break
# Check if any of the dusts have hit the player
if playerHasHitDust(playerRect, dusts):
health -= 5
if health == 0:
if score > topScore:
topScore = score
break
# Check if any of the bullets have hit asteroids.
if bulletHasHitAsteroid(bulletRect, asteroids):
score += 1000
if True:
for a in asteroids:
if a['rect'].colliderect:
asteroids.remove(a)
# Check if any of the tokens have hit the player.
if playerHasHitToken(playerRect, tokens):
score += 10
token += 1
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, asteroids):
health -= 5
if health == 0:
if score > topScore:
topScore = score # set new top score
break
if playerHasHitGhost(playerRect, ghosts):
health -= 10
if health == 0:
if score > topScore:
topScore = score # set new top score
break
if health == 0:
if score > topScore:
topScore = score
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
1 ответ
Ошибка времени выполнения - это тип ошибки, который преднамеренно возникает во время выполнения программы (отсюда и название). Например, в python ошибка времени выполнения может возникать только тогда, когда кто-то пишет
raise RuntimeError
Это означает, что это способ остановить программу, если существует тип ошибки, который программный интерпретатор не обнаружил, но может заставить программу работать не так, как должна. Примером того, когда требуется ошибка времени выполнения, является эта функция (оболочка для функции colorcolor cprint, которая принимает число в качестве цветового аргумента):
import termcolor
def coloredprint(text,color):
if color == 1:
termcolor.cprint(text,color='red')
if color == 2:
termcolor.cprint(text,color='green')
В этом случае функция не будет работать должным образом или не сообщит пользователю о любой ошибке, если цветовой аргумент не равен 1 или 2. Способ решения этой проблемы и упрощение использования вашей программы - ошибка времени выполнения (или более крупные библиотеки будут создавать свои собственные исключения, это не важно). По сути, поскольку аргумент, отличный от 1 или 2, на самом деле является ошибкой в вашей программе (этот питон не будет вас ловить и вызывать), он выдаст ошибку для диагностики пользователем. Вот новая и лучшая версия функции:
import termcolor
def coloredprint(text,color):
if color == 1:
termcolor.cprint(text,color='red')
if color == 2:
termcolor.cprint(text,color='green')
else:
print "colored print function: color argument", color, "is not a viable argument, specify 1 or 0"
raise RuntimeError
Теперь, если пользователь допустит ошибку, программа поймает это как ошибку, вместо того, чтобы не функционировать или делать что-то неожиданное, что затруднит диагностику (а в некоторых случаях потенциально уязвимо). Вот почему ошибка времени выполнения полезна.
Исключения времени выполнения означают некоторую логику сбоя, которая заставила вашу запущенную программу внезапно завершить работу. поскольку вы не написали никакой логики для их обработки, это привело к исключению времени выполнения.