Python exception not raised

Python — Exception not raised

You should switch to to make sure to close the file even if you get exceptions thrown — its the prefered way of file handling, see docs.python.org — reading and writing files I am unable to test this (no stack module — if needed I use lists for that), but this should be faster: Question: is a class that has 5 attributes from which the first one is id, it has a getter and setter so there is no problem with the class but why is not printed any errors when I run this? In the method exception you can add file names or module names in list «filenames» if you want to ignore any unwanted files.

Python — Exception not raised

I’m trying to code a little script that checks whether a file passed as a command line parameter is well or badly parenthesized.

I’ve created an exception to handle the functions stop point but can not seem to raise it properly.

When I test the code in a Python interpreter, it seems to work (ie it recognizes it should the raise the exception, but when I test my file with the sample files I have (that are badly parenthesized), it still prints out that it was successfully checked

import sys from stack import * class BracketException(Exception) : """ Exception qui gère les problèmes de parenthesage : mauvaise parenthèse, mauvais placement etc. """ def __init__(self, char, lineNumber, charNumber) : self.char = char self.lineNumber = lineNumber self.charNumber = charNumber def __str__(self) : return(self.char + " at line " + str(self.lineNumber) + " char " + str(self.charNumber)) def checker(file) : lineNumber = 1 charNumber = 1 stacked = Stack() openers = ["(", "[", ""] inChannel = open(file, "r") for line in file : for char in line : if char in openers : stacked.push([char, lineNumber, charNumber]) print(stacked.top()) elif char in closers : try : if openers[closers.index(char)] == stacked.top()[0] : stacked.pop() else : raise BracketException(char, lineNumber, charNumber) except StackEmptyError : raise BracketException(char, lineNumber, charNumber) charNumber += 1 charNumber = 1 lineNumber += 1 inChannel.close() if not stacked.is_empty() : raise BracketException(stacked.top()[i] for i in range(3)) def __main__() : try : fichier = sys.argv[1] checker(fichier) print("it's checked !") except BracketException as ex : print(ex) except IndexError : print("Wrong number of parameters") except Exception as e : print(e) if __name__ == "__main__" : __main__() 

You are iterating over the given file name, not the created filehandle. File names probably have no unbalanced brackets in them, hence no exception.

def checker(file) : lineNumber = 1 charNumber = 1 stacked = Stack() openers = ["(", "[", ""] inChannel = open(file, "r") # file handle is inChannel for line in file : # iterating over file name, not file handle 
with open(file, "r") as inChannel: for line in inChannel : 

to make sure to close the file even if you get exceptions thrown — its the prefered way of file handling, see docs.python.org — reading and writing files

Читайте также:  Ошибка java util concurrentmodificationexception

I am unable to test this (no stack module — if needed I use lists for that), but this should be faster:

def checker(filename) : lineNumber = 1 charNumber = 1 stacked = Stack() openers = set( "<[(") # sets are better suited for test of "in" closers = set( ">])") # same # mapping between closing bracket at hand and what should be on the stack # also faster then .index()ing into a list open_for_close = < ")":"(",">":" <","]":"[" >with open(filename, "r") as f: for line in f: # iterate over the filehandle for char in line: if char in openers: stacked.push([char, lineNumber, charNumber]) print(stacked.top()) elif char in closers: try : if open_for_close[char] == stacked.top()[0] : stacked.pop() else : raise BracketException(char, lineNumber, charNumber) except StackEmptyError : raise BracketException(char, lineNumber, charNumber) charNumber += 1 charNumber = 1 lineNumber += 1 if not stacked.is_empty() : raise BracketException(stacked.top()[i] for i in range(3)) 

Python Raise an Exception, W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

Exception not raised

class client(): def __init__(self,identitate,nume,cnp,filme_inchiriate,inchirieri): self.__identitate=identitate self.__nume=nume self.__cnp=cnp self.__filme_inchiriate=filme_inchiriate self.__inchirieri=inchirieri def get_identitate(self): return self.__identitate def get_nume(self): return self.__nume def get_cnp(self): return self.__cnp def get_filme_inchiriate(self): return self.__filme_inchiriate def get_inchirieri(self): return self.__inchirieri def set_identitate(self, value): self.__identitate = value def set_nume(self, value): self.__nume = value def set_cnp(self, value): self.__cnp = value def set_filme_inchiriate(self, value): self.__filme_inchiriate = value def set_inchirieri(self, value): self.__inchirieri = value def del_identitate(self): del self.__identitate def del_nume(self): del self.__nume def del_cnp(self): del self.__cnp def del_filme_inchiriate(self): del self.__filme_inchiriate def del_inchirieri(self): del self.__inchirieri identitate = property(get_identitate, set_identitate, del_identitate, "identitate's docstring") nume = property(get_nume, set_nume, del_nume, "nume's docstring") cnp = property(get_cnp, set_cnp, del_cnp, "cnp's docstring") filme_inchiriate = property(get_filme_inchiriate, set_filme_inchiriate, del_filme_inchiriate, "filme_inchiriate's docstring") inchirieri = property(get_inchirieri, set_inchirieri, del_inchirieri, "inchirieri's docstring") def __str__(self): return "ID: " + str(self.get_identitate()) + " Nume: " + str(self.get_nume()) + " CNP: "+ str(self.get_cnp()) from entities import * class validator_client(): def validate_client(self,client): erori=[] if client.get_identitate=="": erori.append("Nu ati introdus ID!") if client.get_nume=="": erori.append("Nu ati indorus nume!") if len(erori)>0: raise ValidatorException(erori) def haha(self,client): if client.get_identitate()=="1": print "hahahah" class ValidatorException(Exception): def __init__(self,erori): self.__erori=erori def get_erori(self): return self.__erori def __str__(self): return self.erori erori = property(get_erori, None, None, None) client1=client("",2,3,4,5) validare=validator_client() try: validare.validate_client(client1) except: ValidatorException print (ValidatorException) 

client() is a class that has 5 attributes from which the first one is id, it has a getter and setter so there is no problem with the class but why is not printed any errors when I run this?

A few things: you aren’t calling that getter, you are getting the method (unless it is a property, in which case, why is it called get). Also, as @Martijn Pieters says in the comments, your except clause is catching all exceptions, then printing the string representation of the ValidatorException class, not the exception instance.

As far as the except clause, I think what you may be looking for is:

except ValidatorException as ve: print(ve) 

Python — Exception not raised, I’ve created an exception to handle the functions stop point but can not seem to raise it properly. When I test the code in a Python interpreter, it seems to work (ie it recognizes it should the raise the exception, but when I test my file with the sample files I have (that are badly parenthesized), it still prints out that it …

Don’t show Python raise-line in the exception stack

When I raise my owns exceptions in my Python libraries, the exception stack shows the raise-line itself as the last item of the stack. This is obviously not an error, is conceptually right, but points the focus on something that is not useful for debugging when you’re are using code externally, for example as a module.

Is there a way to avoid this and force Python to show the previous-to-last stack item as the last one, like the standard Python libraries.

Due warning: modifying the behaviour of the interpreter is generally frowned upon. And in any case, seeing exactly where an error was raised may be helpful in debugging, especially if a function can raise an error for several different reasons.

If you use the traceback module, and replace sys.excepthook with a custom function, it’s probably possible to do this. But making the change will affect error display for the entire program, not just your module, so is probably not recommended.

You could also look at putting code in try/except blocks, then modifying the error and re-raising it. But your time is probably better spent making unexpected errors unlikely, and writing informative error messages for those that could arise.

you can create your own exception hook in python. below is the example of code that i am using.

import sys import traceback def exceptionHandler(got_exception_type, got_exception, got_traceback): listing = traceback.format_exception(got_exception_type, got_exception, got_traceback) # Removing the listing of statement raise (raise line). del listing[-2] filelist = ["org.python.pydev"] # avoiding the debuger modules. listing = [ item for item in listing if len([f for f in filelist if f in item]) == 0 ] files = [line for line in listing if line.startswith(" File")] if len(files) == 1: # only one file, remove the header. del listing[0] print>>sys.stderr, "".join(listing) 

And below are some lines that I have used in my custom exception code.

sys.excepthook = exceptionHandler raise Exception("My Custom error message.") 

In the method exception you can add file names or module names in list «filenames» if you want to ignore any unwanted files. As I have ignored the python pydev module since I am using pydev debugger in eclipse.

The above is used in my own module for a specific purpose. you can modify and use it for your modules.

I’d suggest to not use the Exception mechanism to validate arguments, as tempting as that is. Coding with exceptions as conditionals is like saying, «crash my app if, as a developer, I don’t think of all the bad conditions my provided arguments can cause. Perhaps using exceptions for things not only out of your control but also which is under control of something else like the OS or hardware or the Python language would be more logical, I don’t know. In practice however I use exceptions as you request a solution for.

To answer your question, in part, it is just as simple to code thusly:

class MyObject(object): def saveas(self, filename): if not validate_filename(filename): return False . 
if not myobject.saveas(filename): report_and_retry() 

Perhaps not a great answer, just something to think about.

Raise Exception in Python, The raise Keyword in Python When there are some errors in code during runtime in Python programming, exceptions are raised. We can use the raise keyword to raise exceptions manually. We can also pass the values to the exception to provide more information about the exception and why the program raised it.

Источник

Оцените статью