关于python:处理模块中的异常

Handling exceptions from a module

我正在尝试使用从https://github.com/dbr/tvdb_api导入的"thetvdb"模块。我设法将模块导入到我的代码中,但我试图从模块中获取错误以了解结果。找不到节目、找不到剧集等,如果不破坏脚本,我就无法成功完成。

这是我当前的代码:

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python3
from tvdb_api import tvdb_api
t = tvdb_api.Tvdb()

show_name = raw_input("What is the tv show?")
season_num = int(raw_input("What is the season number?"))
episode_num = int(raw_input("What is the episode number?"))
try:
        episode = t[show_name][season_num][episode_num] # get season 1, episode 3 of show
        print episode['episodename'] # Print episode name
except tvdb_api.tvdb_exception:
        print("error")

我想要的不仅仅是我正在印刷的东西。我尝试过返回,但python告诉我它不在函数中。我认为让我失望的是错误类是空的。

以下是tvdbapi.py文件中异常类的一段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
## Exceptions

class tvdb_exception(Exception):
   """Any exception generated by tvdb_api
   """

    pass

class tvdb_error(tvdb_exception):
   """An error with thetvdb.com (Cannot connect, for example)
   """

    pass

class tvdb_userabort(tvdb_exception):
   """User aborted the interactive selection (via
    the q command, ^c etc)
   """

    pass

class tvdb_notauthorized(tvdb_exception):
   """An authorization error with thetvdb.com
   """

    pass

class tvdb_shownotfound(tvdb_exception):
   """Show cannot be found on thetvdb.com (non-existant show)
   """

    pass

class tvdb_seasonnotfound(tvdb_exception):
   """Season cannot be found on thetvdb.com
   """

    pass

class tvdb_episodenotfound(tvdb_exception):
   """Episode cannot be found on thetvdb.com
   """

    pass

class tvdb_resourcenotfound(tvdb_exception):
   """Resource cannot be found on thetvdb.com
   """

    pass


您可能还需要打印异常:

1
2
3
4
try:
    # ...
except tvdb_api.tvdb_exception as exc:
    print("error:", exc)