raise custom exception in python - python

I could not get what is wrong with the code ? when I execute nothing happens. I am expecting my custom error message.
def testing():
try:
raise Exception('My error!')
except:
pass
testing()

You are raising an exception successfully. But you are catching that with try/except block. So nothing happens unless you describe it in except block.

You are successfully raising an error. And the try/catch statements sees it, and goes to catch as you have raised an error.
To fully customize errors you can declare them as so:
class CustomError(Exception):
pass
raise CustomError("An error occurred")
results in
__main__.CustomError: An error occurred

Related

python exception from module is not caught

I tried to catch an exception from vk_api module. I imported it:
import vk_api
then wrote some code, and then i screwed up my token on purpose so i can check if exception catch works:
try:
vk.method('wall.post', params)
except vk_api.exceptions.ApiError:
print('caught')
but it still gives me an error:
vk_api.exceptions.ApiError: [5] User authorization failed: invalid access_token (4).
What's the problem?
Your error comes from somewhere else in your code. You can have a better idea of where it comes from by using a wider try/except block.
try:
vk_session.auth(token_only=True)
except vk_api.AuthError as error_msg:
print(error_msg)
return
You can check it out an example here.
It seems the correct usage is vk_api.[ErrorName]
Your answer is
try:
vk.method('wall.post', params)
except vk_api.ApiError:
print('caught')

How to print python exception thrown inside exec() function from outside

I am writing a little software for executing python codes and I want to print exceptions. The following function gets executed:
def run(self, mode='activate'):
try:
exec(self.mycode)
except Exception:
print(traceback.format_exc())
There is no information about what exactly will be executed in the exec() function, it can literally be any python code. I want to print an exception thrown (mostly automatically by python due to code errors) somehow like shown, while executing via exec() including the line of code passed into the exec() function where the exception has been thrown.
I so far only managed to get the 'exec(mycode)' as exception code output, but I want the actual line of code that crashed in mycode.
try this :
def run(self, mode='activate'):
try:
exec(your_code)
except Exception as e:
print(e)
This would work!
add this line traceback.print_exc()
def run(self, mode='activate'):
try:
exec(your_code)
except Exception as e:
print(e)
traceback.print_exc()
This would give you the exception information and also will give you line number where the exception/error occurred!

If for Exception

I am teaching myself python and I am still an amateur at remembering all the keywords.
So; simple question, is there to way to use an if statement for an exception?
I can make the exception(NameError) print something. However, I want to use an if statement for if the exception is executed, then do this.
Help would be greatly appreciated!
try-except blocks were designed specifically for the purpose of catching exceptions. if statements are conditionals and are not designed to work with exceptions.
Here's a simple program to demonstrate exception handling:
class SomeException(Exception):
pass
try:
print("In try block.")
raise SomeException()
except SomeException:
print("In except block.")
Additionally, if you need information about the exception, you can use a special except block:
class SomeException(Exception):
pass
try:
print("In try block.")
raise SomeException()
except SomeException as exc: #exc is the exception object
print("In except block.")
When creating exceptions, you can optionally pass one or more arguments to indicate why the exception was raised:
class SomeException(Exception):
pass
try:
print("In try block.")
raise SomeException("message")
except SomeException as exc:
print(exc.args[0]) #Prints "message"
Here's a tutorial on exceptions that I found particularly useful.
A "try-except" block is exactly what you're looking for. Any code in the "try" part is executed normally, but if there's an exception, instead of returning back, it goes to the "except" block.
To phrase it how you were asking, any code in an "except" block runs IF the specific exception was raised/excecuted.
Instead of an error like this:
print(x)
NameError: name 'x' is not defined
You could do this:
try:
print(x)
except NameError:
print("error!")
error!
It will print "error!" IF anything in the try: block resulted in a NameError.
You can also use "else" and "finally" for more control.
Any code in the Else block runs if there were no errors.
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello
Nothing went wrong
Anything in a "finally" block runs after regardless of if there was an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Something went wrong
The 'try except' is finished
I recommend reading the W3 Schools page on Try Except.
https://www.w3schools.com/python/python_try_except.asp
Protip: you can do something like except Exception as e which will save info about the exception to e.

Exception not being caught in try-except block during unit test

I have this in my code:
import api
def do_something():
try:
api = api.Api()
api.call()
except ParseException as e:
logger.exception('Error occurred')
raise ValidationError(detail=e.message)
Basically it calls an API and re-raises the exception with another type.
My test checks the case when the exception is thrown:
#patch('code.api')
def test_exception(self, api_mock):
api_mock.Api.side_effect = ParseException('General Error')
self.assertRaises(
ValidationError,
do_something
)
api_mock.Api.assert_called_once()
However my test fails because ParseException gets thrown and not ValidationError. What is going on?
Note the #patch('code.api') line. This says patch EVERYTHING in code.api. The ParseException is probably in the api module too and thus patched too. If you debug your code you'll see that type(ParseException) is not an instance of Exception but an instance of MagicMock.
I just spent an hour banging my head on the desk, hope this helps someone.

Print Python Exception Type (Raised in Fabric)

I'm using Fabric to automate, including the task of creating a directory. Here is my fabfile.py:
#!/usr/bin/env python
from fabric.api import *
def init():
try:
local('mkdir ./www')
except ##what exception?##:
#print exception name to put in above
Run fab fabfile.py and f I already have ./www created an error is raised, but I don't know what kind, so I don't know how to handle the error yet. Fabric only prints out the following:
mkdir: cannot create directory ‘./www’: File exists
Fatal error: local() encountered an error (return code 1) while executing 'mkdir ./www'
Aborting.
What I want to do is be able to find out the error type so that I can except my errors properly without blanket statements. It would be really helpful if an answer does not just tell me how to handle a mkdir exception, but print (or otherwise find the name to) any exception I may run into down the line (mkdir is just an example).
Thank you!
The issue is that fabric uses subprocess for doing these sorts of things. If you look at the source code for local you can see it doesn't actually raise an exception. It calls suprocess.Popen and uses communicate() to read stdout and stderr. If there is a non-zero return code then it returns a call to either warn or abort. The default is abort. So, to do what you want, try this:
def init():
with settings(warn_only=True):
local('mkdir ./www')
If you look at the source for abort, it looks like this:
10 def abort(msg):
21 from fabric.state import output
22 if output.aborts:
23 sys.stderr.write("\nFatal error: %s\n" % str(msg))
24 sys.stderr.write("\nAborting.\n")
25 sys.exit(1)
So, the exception would be a SystemExit exception. While you could catch this, the proper way to do it is outlined above using settings.
It is nothing to handle with exception, it is from the fabric api
try to set the entire script's warn_only setting to be true with
env.warn_only = True
Normally, when you get an uncaught exception, Python will print the exception type along with the error message:
>>> raise IOError("Error message.")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: Error message.
If that's not happening, you're probably not getting an exception at all.
If you really want to catch an arbitrary exception and print it, you want to catch Exception or BaseException. BaseException will include even things like KeyboardInterrupt, though, so be careful with that.
def init():
try:
local('mkdir ./www')
except BaseException as e:
print "local() threw a", type(e).__name__
raise # Reraise the exception
In general:
try:
some_code()
except Exception, e:
print 'Hit An Exception', e
raise
Will tell you what the exception was but if you are not planning on actually handling some of the exceptions then simply getting rid of the try: except: lines will have exactly the same effect.
Also if you run your code under a debugger then you can look at the exception(s) that you hit in more detail.
def init():
try:
local('mkdir ./www')
except Exception as e:
print e.__class__.__name__
That's all there is to it!
edit: Just re-read your question and realized that my code would only print "Fatal" in your case. It looks like fabric is throwing an error and returning their own error code so you would have to look at the documentation. I don't have any experience with fabric so I'd suggest to look here if you haven't already. Sorry if this isn't helpful!

Categories

Resources