I've 3 .jsp files. index.jsp and sqrtcalculator.jsp and error.jsp.
In index.jsp there's a text field and a button. In sqrtcalculator.jps there's the, well, calculator.
Now, when I leave the field empty and press the button, an expection is called, because the field is empty. And I can then reroute to an individual error.jsp site to display the errors, and exception stack like
<%= request.getAttribute("javax.servlet.error.request_uri") %>
<%= exception.getMessage() %>
<%= exception %>
etc.
Problem is, when I enter -5 in the textfield, I can't get an exception, because Math.sqrt(-5) doesn't return an error but "NaN".
How can I force it to be an exception? The idea is to reroute the user to an individual error.jsp and displaying the errors. But like I said Math.sqrt(-5) doesn't return errors or exceptions but "NaN" textstring.
I don't want something like this just FYI
<%if (NaN){
%>
<p>Nope, Square root from negative numbers is not defined!</p>
<%}
%>
Warning, the test for NaN in the previous answer is wrong (NaN is NOT equal to itself). In Java the better way to test for NaN is
if (Double.isNaN(answer)) {
// throw exception
}
alternatively
if (answer != answer) {
}
While this second version will work, it is sure to puzzle those not aware of the curious behaviour of NaN.
How about:
if (x >= 0.0) {
return Math.sqrt(x);
} else {
throw new ArithmeticException("Square root from negative numbers is not defined!");
}
Note that ArithmeticException is a subclass of RuntimeException and therefore does not need to be declared in the throws clause of your function.
It's presumably returning NaN because square roots of negative numbers are indeed defined, they're just not real numbers. Is there any reason you can't do this?
if(Double.isNaN(answer))
throw new ArithmeticException("Answer unreal");
That should tickle your exception handling code, but the source line might just be a few lines off. I've never written JSP, but that makes sense in Java.
I'm not very good in jsp but afaik you should be able to use basic java code.. so i'd check my result for NaN and throw an exception
if (NaN == result)
throw new Exception("NaN");
you'll have to adjust the if ;)
I would ask why you're using scriptlets in JSPs.
If your app really is just three pages (index.jsp and sqrtcalculator.jsp and error.jsp), then maybe it's justifiable.
But my general recommendation would be to stay away from scriptlet code in JSPs and prefer JSTL. Have those calculations done in a server-side component, using a Model-2 MVC arrangement.
If your app really consists of only three pages, re-architecting it to use Model-2 MVC would not be difficult to do. You might find that it's far more extensible that way. If you're unfamiliar with Model-2 MVC you can read about it here. If you're familiar with it, this might be a self-contained problem that's small enough to let you see where it could provide some value in future projects.
Another thought would be to add complex numbers to your calculator, because the square root of negative numbers is indeed a valid concept. It just requires imaginary numbers. Maybe your calculator needs to be extended to maximize usefulness.
I can't seem to get it to work....
if (d < 0){
throw new Exception("Negative Numbers not possible!");
}
d is a double read via d_string = request.getParameter("numberfromtextfield") and converted to double via double d = Double.parseDouble(d_string);.
This is what Eclipse is telling me: http://pastebin.ca/1691409
Related
I've just been asked to look after some classic asp code, currently running on IIS6, I'm on IIS7...and the existing code is throwing up a few errors I'm not sure I'd expect. Has anything changed in the way it should behave/is there a way to make it behave like it used to so I can fix these issues as it gets rebuilt?
The first is this:
If NOT ISNULL(fieldforfiltering) then
fieldforfiltering = TRIM(fieldforfiltering)
convertbackfield = Replace(fieldforfiltering, """, chr(34))
.....
End If
This is complaining that fieldforfiltering is null on the 3rd line. This I would expect from my C# life as the whole body of the if is not enclosed, so only the first line would get run (although there is an End If, so I'd sort of expect that to work...). However, it's working on IIS6, just not IIS7.
The second is a Cint issue
totcat = rs("totcat")
totalpage = totcat / 50
...throws a Type Mismatch error on the second line. If I change it to
totalpage = CInt(totcat) / 50
...it's fine. Again, I sort of know why - but why would that work on IIS6 and not IIS7?
I'd like to get it working as it is (as it clearly does work) and then go through and fix these over the coming months...it's too big a job to do it in one go.
It sounds like you might be running with different options: Option Strict On vs Option Strict Off, for example.
I'm working on a asp based (not .net) site, which spans about 400 odd pages... Now, throughout the site there're ASP and VBScript errors, such as:
Microsoft VBScript runtime error '800a000d'
Type mismatch: 'Cdate'
/MySite/page.asp, line 71
(The above happened when I put in characters into a 'date' field. I know its VBScript in this case, but I get plenty all over.)
Now, I know I can avoid this scenario with client side validation (jQuery for example), but when such things do happen, how do I code up a default 'error' page? You hit the error, and instead of showing you the above, you get redirected to a generic 'error' page?
I've looked up some of this, and found the ASP 'On Error Resume Next' thing, but I haven't found any viable examples. Each one is tailored to a specific error (like dividing 5 by 0), and I really don't want to code up like 400+ potential error messages.
You could create custom error pages, via IIS. I'm not sure what version you're running, etc - but this should give you a good jumping off point. http://support.microsoft.com/kb/224070
You add following code in top in your page.
<% on error resume next%>
.
..
....
(Other code is above instead of point(.))
Then you add
<% if err then
response.redirect("err.page?code="&err.code)
end if%>
And you define error message in your generic error page according to error number.
if you ask same question for client side. You can try and catch code block for possible code clock that will can throw.
For examle
<script language="text/javascript">
try
{
//Code that will can throw error is here.
}
catch(err)
{
document.href.location="genericerrorpage.asp?err=" + err.code;
}
}
</script>
I'm working in some old code which was originally designed for handling two different kinds of files. I was recently tasked with adding a new kind of file to this code. Most of my problems were solved by filling out an extensive XML file with a new entry that handled everything from what lists were named to how the file is written in plural lower case. But this ended up being insufficient, as there were maybe 50 different places in 24 different code files where I had to update hardcoded switch-statements that only branched for the original two file types.
Unfortunately there is no consistency in this; there are methods which operate half from the XML file, and half off of hardcode. Some of the files which look like they would operate off of the XML file don't, and some that I would expect that I'd need to update the hardcode don't need it. So the only way to find the majority of these is to run through testing the whole system when only part of it is operational, finding that one step to fix (when I'm lucky that error logging actually tells me what is going on), and then running the whole thing again. This wastes time testing the parts of the code which are already confirmed to work, time better spent testing the new parts I have to add on top of it all.
It's a hassle and a half, and to my luck I can expect that I will have to add yet another new kind of file in the near future.
Are there any solutions out there which can aid in this kind of endeavour? Something which I can input some parameters of current features, document what points in a whole code project actually need to be updated, and run something nice the next time I need to add a new feature to the code. It needn't even be fully automated, something that'll help me navigate straight to the specific points in everything and maybe even record what kind of parameters need to be loaded.
Doubt it matters specifically, but the code is comprised of ASP.NET pages, some ASP.NET controls, hundreds of C# code files, and a handful of additional XML files. It's all currently in a couple big Visual Studio 2008 projects.
Not exactly what you are describing, but if you can introduce a seam into the code and lay down some interfaces you can break out and mock, a suite of unit/integration tests would go a long way to helping you modify old code you may not fully understand well.
I completely agree with the comment about using Michael Feathers' book to learn how to wedge new tests into legacy code. I'd also strongly recommend Refactoring, by Martin Fowler. What it sounds like you need to do for your code is to implement the "Replace conditionals with polymorphism" refactoring.
I imagine your code today looks somewhat like this:
if (filetype == 23)
{
type23parser.parse(file);
}
else if (filetype == 69)
{
filestore = type69reader.read(file);
File newfile = convertFSto23(filestore);
type23parser.parse(newfile);
}
What you want to do is to abstract away all the "if (type == foo)" kinds of logic into strategy patterns that are created in a factory.
class FileRules : pReader(NULL), pParser(NULL)
{
private:
FileReaderRules *pReader;
FileParserRules *pParser;
public:
void read(File* inFile) {pReader->read(inFile);};
void parse(File* inFile) {pParser->parse(inFile);};
};
class FileRulesFactory
{
FileRules* GetRules(int inputFiletype, int parserType)
{
switch (inputFiletype)
{
case 23:
pReader = new ASCIIReader;
break;
case 69:
pReader = new EBCDICReader;
break;
}
switch (parserType)
... etc...
then your main line of code looks like this:
FileRules* rules = FileRulesFactory.GetRules(filetype, parsertype);
rules.read(file);
rules.parse(file);
Pull off this refactoring, and adding a new set of file types, parsers, readers, etc., becomes as simple as writing one exclusive to your new type.
Of course, go read the book. I vastly oversimplified it here, and probably got stuff wrong, but you should get the general idea of how to approach it from this. I can also recommend another book, "Head First Design Patterns", which has a great section on the Factory patterns (if you like those "Head First" kinds of books.)
I am very new to asp and having following problem
I am getting 2 values from 2 column, from database and when i try to multiply them, its giving following error
Error Type:
(0x80020009)
Exception occurred.
This is my code
totalPrice = totalPrice + rs("ProductQunaity") * rs("ProductPrice")
Even if someone can tell me what should be "Title" of this question, that would be great.
In case the error that amphetamachine pointed out is only in your code here at SO and not in the original code, please make sure that you don't have any type errors ( ;) ) with the values either.
totalPrice = totalPrice + CInt(rs("ProductQuantity")) * CDbl(rs("ProductPrice"))
where CInt() converts a value to an integer, and CDbl() converts a value to a double.
However, if you're very new to ASP, I'd recommend going straight to ASP.NET - ASP is a technology that hasn't developed in the last decade, while ASP.NET is Microsoft's new, fully supported (and pretty awesome) web development platform.
I'd recommend you start with ASP.NET MVC, since it is usually a lot cleaner, and it's straightforward to output the html you want. This and this are two good places to start.
Are you sure you typed that correctly?
# (what's this?) ---v
totalPrice = totalPrice + rs("ProductQunaity") * rs("ProductPrice"`)
Whenever you have errors like this, the best way to debug them is to response.write all the values out, then response.end before the line throwing the error is run. You can then inspect the values and attempt to work out why they are not compatible.
I have a weird problem where the "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints." error sometimes pops up when I am trying to build my project.
The line in question throwing the error was auto-generated code in the designer file for the dataset. To find out the offending table, I used the following code:
Try
Me.Adapter.Fill(dataTable) <--Breakpoint here on the offending line
Catch ex As Exception
For Each TRow As DataRow In dataTable.Rows
If TRow.HasErrors Then
Trace.Write(TRow.RowError)
End If
Next
End Try
Funnily enough, as soon as I run the project after putting in the above code and breakpoint, the error disappears. I assume this has something to do with the code being regenerated. All data is presented successfully, and the project compiles without errors.
However, this has happened often enough for me to frustrate me. Anybody know what might be causing the error and how I can isolate it?
What unique constraint are you placing on the datatable and have you verified that the data your passing in doesn't have any duplicates? If this is coming from a shared database perhaps someone else is modifying the data which could be causing the randomness.
Edit
If that code is exactly as what you have (And forgive me my vb.net is not as strong as my C#). Wouldn't it swallow the exception? In C# we need to rethrow the error.
Add a Trace.Write() right before you go into your for loop.
You are probably working with a typed dataset, or have some code configuration on it. Also you might be reading from one table, and then adding data from another.
In any of those cases, you really want to look into any inconsistencies between the schema. If it is a typed dataset / or configured in code, check its definition, and look for anything different from the sql table. If you are reading from 2 different tables, check the definition of both tables.
Figured it out finally!
The reason the breakpoint wasn't being hit was because the code in question was auto-generated, and had the attribute "DebuggerNonUserCodeAttribute". In addition, in my VS settings, I had set the debugger to "Just my code".
When I ran the code again, and the breakpoint wasn't hit, I noticed the breakpoint icon had changed to a warning. Hovering showed this:
"The breakpoint will currently not be hit. Breakpoints cannot be set in a method or class with the 'DebuggerNonUserCode' attribute when the debugger option 'Just My Code' is enabled."
Ouch!
Once I had removed the "Just My Code" debugging option, the breakpoint was hit, and I discovered that one of the rows had a NULL value in one of the columns which had a non-null constraint. Stupid ole' me!
You should use this code before you fill DataTable :
var dt = new System.DataTable.DataTable();
dt.Clear();
dt.Rows.Clear();
dt.Columns.Clear();