Can I raise and handle exceptions in the same function - custom-exceptions

I am raising an exception and trying to handle the exception in snippet. The raising exception part and handling exception part are done in a function. Is it wrong to do so?
import sys
def water_level(lev):
if(lev<10):
raise Exception("Invalid Level!")
print"New level=" # If exception not raised then print new level
lev=lev+10
print lev
try:
if(level<10):
print"Alarming situation has occurred."
except Exception:
sys.stdout.write('\a')
sys.stdout.flush()
else:
os.system('say "Liquid level ok"')
print"Enter the level of tank"
level=input()
water_level(level) #function call
The output is not handling exception. Can someone explain me why?

It is better to just raise the exception in the function and then catch it it when you call the function so your function does not do too much and your error handling is independent. And it makes your code simpler.
Your code never reached your except clause because if the water level is too low it raises an exception and jumps out of the function and if it was okay it just reaches the else clause. The print statement in your try clause is also never reached because it is the same condition than the one that raises your exception and that one jumps out.
Your code should be something like that...
import sys
import os
def water_level(level):
#just raise exception in function here
if level < 10:
raise Exception("Invalid Level!")
level = level + 10
print("New level=") # If exception not raised then print new level
print(level)
#function call
print("Enter the level of tank")
#cast to int
level=int(input())
try:
#call function in here
water_level(level)
#catch risen exceptions
except Exception as e:
sys.stdout.write('\a')
sys.stdout.flush()
#print exception(verification)
print(e)
print("Alarming situation has occurred.")
else:
os.system('say "Liquid level ok"')
Note that i corrected some other flaws
import os was missing
you should cast your input() to a number so you can do number comparisions and additions
try to avoid to catch the least specific Exception Exception because you will catch every other Exception too.(thats why i added the print(e)) -> think about custom exceptions

Related

Test that an exception is handled correctly with pytest

I have a block of try-exception code and I want to test if the block works properly? I wonder if there is a way to test this block with a unit test using pylint? This is the snipent I have:
class data_type(Enum):
SESSIONS = 0
RUNS = 1
def find_filter(data_type)
try:
if data_type.name == 'SESSIONS':
return {}
elif data_type.name == 'RUNS':
#Filter out rerun jobs
filter = {
"filter":{
"attName":"is_rerun",
"operand":"IN",
"#c":".InFilter",
"values":["FALSE"]
}
}
return filter
except AttributeError as erro:
loghandler.critical('Error in creating count query: {}'.format(erro))
I want to test if the data_type is not a valid enum member, the exception catches it before the execution goes to if statement. For example if:
find_filter('')
is called I like to see that the except AttributeError as erro captures the error and the error is logged.
Is there a way to do that?
PS: I know with pytest.raises() I can test if a raised error is really raised? But as far as I understand pytest.raises() does not work for testing the exception block of a try-exception case.
Any suggestion please?
Thanks.

Error handling of PipelineModel.load(PATH) if path doesn't exist Pyspark

I want to do an error handling of PipelineModel.load(PATH) i.e want to check if path exists if it doesn't exist, I want to exit the code so was trying try except block but don't exactly know what the error I should be expecting, Below is the snippet for same
try:
pipelineModel = PipelineModel.load(PATH)
except InvalidInputException:
print('Path Does not exist')
sys.exit(0)
Below is the error message
NameError: name 'InvalidInputException' is not defined
try:
pipelineModel = PipelineModel.load(S3LOC)
except Exception as e:
print('Exception Message ',e.args)
print('Model is not deployed')
sys.exit(0)
This snippet worked for me

Python3 Catch errors when from self.connect(('badhost',6667))

Looks like asyncio is the module to use. I'll leave this question up anyway, because it doesn't look like there is a way to catch specific errors with asynchat.
class mysocket(asynchat.async_chat):
terminator = b'\n'
def __init__(self,sock=None):
asynchat.async_chat.__init__(self,sock)
self.create_socket()
# Try always succeeds with self.connect
try:
self.connect(('badhost',6667))
print('command always successful')
except:
print('This never gets printed')
How do I catch errors from the self.connect() method that causes an uncaught exception.
error: uncaptured python exception, closing channel <main.mysocket badhost:6667 at 0x7f0a03e66a58> (:[Errno 111] Connection refused [/usr/lib/python3.4/asyncore.py|read|83] [/usr/lib/python3.4/asyncore.py|handle_read_event|439] [/usr/lib/python3.4/asyncore.py|handle_connect_event|447])
All that is left to try is overwrite the handle_connect_event() method and put asyncore.handle_connect_event(self). I would like to get a professional answer to this dilemma.
Try to override default handle_error method:
def handle_error(self):
t, v, tb = sys.exc_info()
if t == socket.error:
# do smth with it
print("Connect error")

How to make Play print all the errors

In our Scala, Play, Reactivemongo we have a big problem with exception handling - when there is an error, in Iteratee/Enumeratee or in Actor system Play just swallows it, without logging any error to the output. So we effectively need to guess where, and why this error might happen.
We made Globals override, to always print the error, and specified logger.root=TRACE, but still saw no output, from which we could analyse our problems.
How to forcebly make Play print all the errors
Didn't found the way to explicitly log everything but there is a way to log exceptions locally.
I did this:
def recover[T] = Enumeratee.recover[T] {
case (e, input) => Logger.error("Error happened on:" + input, e)
}
and then used it on all the enumeratees that can produce errors
def transform(from: Enumerator[From]): Enumerator[String] = {
heading >>> (from &> recover[From] ><> mapper) >>> tailing
}
here, mapper throws exception, and they are all logged.
I think your problem is with how Future works in scala, let's take the following exemple :
val f :Future[Int]= Future {
throw new NullPointerException("NULL")
1
}
f.map(s1 => {println(s" ==> $s1");s" ==> $s1"})
This code will throw an exception but the stack trace will not be printed as futures handle the error.
If you want to get the error that happened you can
just call:
f.onComplete{
case Success(e) => {}
case Failure(e) => e.printStackTrace()
}
e is a throwable that you can use as you want to handle the error.
At the solution I used, is override through ErrorHandling in Play https://www.playframework.com/documentation/2.4.2/ScalaErrorHandling, basically creating ErrorHandler that logs all the errors, with needed detalization.

How to Display exception thrown in "should produce [exception]” in ScalaTest

I would like to display the Exception message thrown in scala test.
" iWillThrowCustomException Method Failure test.
" should "Fail, Reason: Reason for failing. " in {
evaluating {
iWillThrowCustomException();
} should produce [CustomException]
}
If CustomExeption will throw different types of messages for differnt inputs , say
(for -ve amount - Amount is less than zero, for chars in amount - Invalid amount),
how to display the message which is thrown in the block, becuase it will through
the CustomException and it will show Test Success, but for which senario it has thrown the error
Alternatively you can check out intercept:
val ex = intercept[CustomException] {
iWillThrowCustomException()
}
ex.getMessage should equal ("My custom message")
evaluating also returns an exception so you can inspect it or print the message. Here is example from the ScalaDoc:
val thrown = evaluating { s.charAt(-1) } should produce [IndexOutOfBoundsException]
thrown.getMessage should equal ("String index out of range: -1")
As far as I know, you can't include exception message in the test name.
What you can do, is to add additional information about test with info():
"iWillThrowCustomException Method Failure test." in {
val exception = evaluating { iWillThrowCustomException() } should produce [CustomException]
info("Reason: " + exception.getMessage)
}
This will be shown in the test results as nested message. You can find more info about this in ScalaDoc.