PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

[FIXED] How to catch an error thrown inside an imported module

 October 26, 2022     exception, oop, python, python-module     No comments   

Issue

I have a custom module with a function, and I am importing it to my main file. When there is an exception raised in the module, I want to catch it in the main file.

Is this possible? I'm having a hard time finding any examples of this online or in the exception documentation.

Example:

exceptionStuff.py

class My_Error(Exception):
    pass

def Fail_Func():
    raise Exception

main.py

from myModules.exceptionStuff import My_Error

try:
    My_Error()
except:
    print('caught')

The exception doesn't get caught here.


Solution

If you reorganize exceptionStuff.py like this

class My_Error(Exception):
    pass

def Fail_Func():
    raise My_Error

And your main file like this

from exceptionStuff import My_Error, Fail_Func

try:
    Fail_Func()
except My_Error as e:
    print(e.__class__.__name__)
    print('caught')

You will successfully catch an exception of type My_Error.

Output:

My_Error
caught


Answered By - JRose
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing