Using exceptions
Basically I have this
for(int i=0; i<6; i++){
guess=Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter guess" + " " + (i+1) + " " + "(between 1 and 6)" ));
do {
if (guess[i]<1 || guess[i]>6){
JOptionPane.showMessageDialog (null, "That's not between 1 and 6, try again", "Invalid", JOptionPane.WARNING_MESSAGE);
guess[i]=Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter guess" + " " + (i+1) + " " + "(between 1 and 6)"));
}while (guess[i]<1 || guess[i]>6);
I want to make it so that it catches the NumberFormatException if the user accidentally inputs a character instead of a number. How do I go about this? I know I have to use "try" and "catch", but at what bit of the above piece of code would I user it?
Here's how NumberFormatException could be handled.
String str = null;
for(int i = 0; i < 6; i++) {
do {
str = JOptionPane.showInputDialog(null, "Please enter guess" +" " +(i+1)
+" " +"(between 1 and 6)");
// Handle the NumberFormatException.
try {
guess[i] = Integer.parseInt(str);
} catch(NumberFormatException nfe) {
nfe.printStackTrace();
// Do something like setting the guess value
// to a negative number and prompting for input again.
guess[i] = -1;
if (guess[i] < 1 || guess[i] > 6) {
JOptionPane.showMessageDialog(null, "That's not between 1 and 6, try again",
"Invalid", JOptionPane.WARNING_MESSAGE);
} else {
break;
} while(true);
}In your code snippet, you need not repeat the same lines again.
Similar Messages
-
How to find the list of Queries/Reports which are using Exceptional Aggregation in SAP BI?
Hi All,
We are interested to know how to find the list of Queries/ Reports which are using Exceptional aggregation in SAP BI.
Please let us know is there any table's to check the list of reports using Exceptional Aggregation in SAP BI.Hi,
Here you go..
1) Go to table RSZCALC and get list of ELTUID where AGGREXC is not INITIAL and AGGRCHA is not initial; now you get only exception aggregation set based on some chars. Also you can further add STEPNR = 1 since your intention is just to get query name , not the calculation details; this will reduce number of entries to lookup and save DB time for next steps.
Here you will get list of exception aggregation UUID numbers from which you can get properties from RSZELTDIR.
2) Pass list of RSZCALC-ELTUID to table RSZELTXREF - TELTUID and get list of RSZELTXREF -SELTUID - this table stores query to it's elements maping kind.
3) Now again pass RSZELTXREF - SELTUID into same table but into different field RSZELTZREF - TELTUID and get RSZELTXREF - SELTUID
This step you get query reference sheet or column or query general UUID for next step.
4) Pass list of RSZELTXREF - SELTUID into RSZELTDIR - ELTUID with DEFTP as 'REP'. Now you get list of query names in RSZELTDIR - MAPNAME and description in TXTLG.
Note: you can also get the reference chars used for exception aggregation from RSZCALC - AGGRCHA field.
Hope this helps.
Please keep in mind, it might take more time depends on how many query elements you have in the system...
Comments added for better DB performance by: Arun Thangaraj -
How to use Exceptions for a function module
Hi folks,
I have created a new function module.Its working fine, but i am not aware of using exceptions for a function module. I hav just declared an exception in the 'exception' tab. Could any body explain me how to use that in my FM source code....Thanks...Hi Shyam,
Have a look at this,
START-OF-SELECTION.
gd_file = p_infile.
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
filename = gd_file
has_field_separator = 'X' "file is TAB delimited
TABLES
data_tab = it_record
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17.
IF sy-subrc NE 0.
write: 'Error ', sy-subrc, 'returned from GUI_UPLOAD FM'.
skip.
endif.
Regards,
Sai -
Should i use Exceptions in my classes like this?
try {
auth.loginUser(userName, userPassword);
System.out.println("User logged in.");
catch (InvalidUserException e1) {
System.out.println("User does not exists.");
catch (PasswordDoesNotMatchException e2) {
System.out.println("Password is incorrect.");
catch (SystemException e3) {
System.err.println("System error.");
// logging to file, etc.
System.out.println("Please, try login later.");
..or maybe i should use Exceptions only for "real" Java errors? (file not found, division by zero, etc.)
Thanks!Well, the word "exception" says a lot here; you throw
an exception when something exceptional happens, in
other words: something you normally don't expect to
happen. And you offer control returned value? Bad solution, because I can
want not only true/false answer, but and reason why it happen. In your offer I must use String answer = "user OK"; or "answer 200"
This quote is from Thinking in Java:
In C and other earlier languages, there could be several of these
formalities, and they were generally established by convention and not as
part of the programming language. Typically, you returned a special value
or set a flag, and the recipient was supposed to look at the value or the flag
and determine that something was amiss. However, as the years passed, it
was discovered that programmers who use a library tend to think of
themselves as invincible�as in, �Yes, errors might happen to others, but
not in my code.� So, not too surprisingly, they wouldn�t check for the error
conditions (and sometimes the error conditions were too silly to check
for1). If you were thorough enough to check for an error every time you
called a method, your code could turn into an unreadable nightmare.
Because programmers could still coax systems out of these languages they
were resistant to admitting the truth: This approach to handling errors
was a major limitation to creating large, robust, maintainable programs.
We can analize it how Login use case.
Flow: If use enter good login and passwd, when ....
Exception: bad passwd, bad login, ban IP and other.
ciau,
kafka -
Can we use exceptions and conditions at the same time?
can we use exceptions and conditions at the same time? Are there any dependencies between exceptions an conditions?
Exceptions are used when there are some mistakes , or exceeds the supposed values, we can highligt that in different colours for enabling the validator to notice easily. In this we are giving conditions for considering the value as exceptions. suppose, if the values is out of the range -1 to +1 then exception.
But conditions can be considered as the restrictions given in measure level also. So please elaborate what you meant by conditions -
May I use Exception Handling for validation ?
Hello All,
Can any one know about that may i use exception handling for validation in my report program.
Please if its possible then give me some Example...
Thanks.Hi Niraj,
Exception is not at all raised or handled in the given example.
There are so many document available in the SCN regarding OO ABAP you can read that.
As far as validation of a field ( Selection screen ) of course we can do that but I don't see any advantage more over it will make your code unnecessarily complex.
Regards
Bikas -
KPI Calculation and using Exception
Hi all,
In my current project we have to calculate certain KPIs of my company and have to compare them with target value and put the result in Green or yellow or red zone using exception.
EX:- KPI 1 = (# of associates having completed training)/(Total # of planned associates to attend training)×100
So here first I have to calculate KPI 1 and put the result % in KPI and then if you see below table as next step
Target Value KPI Color zone
Pharma 10% 20% Green
America 20% 30% Green
US 50% 40% Yellow
Europe 30% 15% Red
CH 40% 20% RED
DE 50% 10% RED
In above table we need to check the KPIs
Green if KPI>Target value
Yellow if KPI is + or - 10% of target value
Red if KPI is < 10% of Target value
Now my question is how to calculate the KPI and target value difference, how to put them in Exception to get color zones display in report using above 3 conditions?
Please suggest...
Thanks,
Preethican you please elaborate your solution?
to be more specific my requirement is as below.
Please treat each as a column in bellow with respective values.
Associates completed training, Total no. of associates planned to take training, Ratio/KPI, Target value , difference
20 , 30, 67% ( 20/30*100) , 80%, 13% (difference of Target value value and KPI/Ratio)
we have to check below conditions and give coloring to KF ratio/KPI
If ratio/kpi > target value
ratio/KPI= Green
elseif
Target value - ratio/kpi <10%
ratio/KPI = Yellow
else
ratio/KPI = RED (i.e, target value - ratio >10%)
Now can you help me....
Thanks,
preethi -
Why we use exception ???
Why we use Exception ??anyone knows what are the 3 keys point below describe about..??
There are 3 main Advantages of using Exception
1.Separates error handling code from "regular code
2.Propagating erros up the call stack (without tedious programming)
3.Grouping error type and error differentiation
TQ.hi,
1) you can catch those exceptions and write extra classes for handling/log them, so you do not have to do between the lines of source
2) if an uncaught exception happens an errorstack will be invoked. On the stack you can see, where the exception started and which classes are involved
3) you can have very special erros, for example all errors which occurs on files (normally it is an IOException), you can define your own exceptions so you can say, i.e. line 503 doesn't contain what it should.
With this way you can resolve very well where an exception raises and why it happens.
hope it answers
regards
freak -
How to create counter with charcteristic values using exception aggregatio
Dear Experts,
Can some one help me on the below issue
Requirement : Creating a counter with char ( accounting doucment number) in the query by using exception aggregation & summarize on totals with CKF.
Note : i dont have any keyfigure called counter in my infoprovider
Please let me know how to create it.
I came to know that create new CKF & FV with replacemtn path with IO(Account document number) & use FV in CKF. is this true & works??
Please let me know how i should proceed ahead??
Thanks
SurendraI have resoloved by own
By createin zckf--> fv choosing replacement path with IO as reference and key.
then excepetion aggreation chosen : counter for all detailed values & check the checkbox calucate after aggreagation.
Thanks -
Using EXCEPT and INTERSECT (Transact-SQL) with a Twist
I understand how to use EXCEPT and INTERSECT BUT how Do use it with two different servers? I have the production database on server1, the conversion database on server2. The databases are identical EXCEPT there is more (new) data in CONVERSION.
I want one query that properly coded returns the differences between production and conversion. I expect to run EXCEPT first (PRODUCTION on left, CONVERSION on right), then I will run INTERSECT (PRODUCTION on left, CONVERSION on right).
How do I get the full network path: SERVER/DATABASE/TABLE?
USE SERVERNAME1.PRODUCTION;
SELECT person_id
,person_name
FROM person_detail AS x
USE SERVERNAME2.CONVERSION;
SELECT person_id
,person_name
FROM person AS y
GO
SELECT *
FROM x
EXCEPT
SELECT *
FROM y;Hi,
You can use
OPENROWSET to get the data from the remote server and then you can use simple EXCEPT and INTERSECT as you already know
Something like:
SELECT ProductID FROM Production.Product
INTERSECT
SELECT ProductID
FROM OPENROWSET(
'SQLNCLI',
'Use your connection string here to the remote server',
'SELECT ProductID FROM Production.WorkOrder ;'
Ronen Ariely
[Personal Site] [Blog] [Facebook] -
Cursor using exception issue reg
Dear all,
I have created one procedure and it is working perfectly ,but i want two point to be included in this code
point 1: i want to trap any error through Exception which i need to include in this code
so in which section i need to include the exception section and what type of useful exception i should include.
point 2: i want status of no of row being updated while processing
i need ur suggestion kindly
regards
Laxman
create or replace procedure freereq24hr
as
begin
FOR mtid_cur_rec in (select a.miniteamid from auto_miniteam a,miniteam m
where job_type=5 and
a.miniteamid=m.miniteamid) LOOP
FOR age_cur_rec in (SELECT requestID
FROM Request
WHERE miniteamid IN (
SELECT childMiniTeamID
FROM MiniTeamTree
WHERE childMiniteamID = mtid_cur_rec.miniteamid AND
parentMiniteamID IN(mtid_cur_rec.miniteamid)
) AND
requestTypeCode = 1 AND
statusCode IN (2,3) AND
assigned_PersonID is NULL AND
lastmoddate < sysdate - 1) LOOP
IntNotesHistoryInsert(age_cur_rec.requestid,'FREE REQUEST 24 HR');
UPDATE Request
SET statusCode = 1, assigned_PersonID = NULL
WHERE requestID = age_cur_rec.requestid;
commit;
END LOOP;
END LOOP;
END;point 1: i want to trap any error through Exception which i need to include in this code
so in which section i need to include the exception section and what type of useful exception i should include. What kind of error do you expect? Seeing your code i dont think you need to handle any specific exception.
>
point 2: i want status of no of row being updated while processing You can use sql%rowcount to get that details.
create or replace procedure freereq24hr
as
begin
FOR mtid_cur_rec in (select a.miniteamid from auto_miniteam a,miniteam m
where job_type=5 and
a.miniteamid=m.miniteamid) LOOP
FOR age_cur_rec in (SELECT requestID
FROM Request
WHERE miniteamid IN (
SELECT childMiniTeamID
FROM MiniTeamTree
WHERE childMiniteamID = mtid_cur_rec.miniteamid AND
parentMiniteamID IN(mtid_cur_rec.miniteamid)
) AND
requestTypeCode = 1 AND
statusCode IN (2,3) AND
assigned_PersonID is NULL AND
lastmoddate < sysdate - 1) LOOP
IntNotesHistoryInsert(age_cur_rec.requestid,'FREE REQUEST 24 HR');
UPDATE Request
SET statusCode = 1, assigned_PersonID = NULL
WHERE requestID = age_cur_rec.requestid;
commit;
END LOOP;
END LOOP;
END;But in general i would rewrite your code to avoide two for loop and just have a single thing.
create or replace procedure freereq24hr
as
begin
for i in (
select requestId
from request r
join miniteamtree m
on r.miniteamid = m.childminiteamid
join auto_miniteam a
on a.miniteamid = m.childminiteamid
and a.miniteamid = m.parentminiteamid
join miniteam mi
on a.miniteamid = mi.miniteamid
where job_type = 5
and requestTypeCode = 1
and statusCode IN (2,3)
and assigned_PersonID is NULL
and lastmoddate < sysdate - 1
loop
IntNotesHistoryInsert(i.requestid,'FREE REQUEST 24 HR');
UPDATE Request
SET statusCode = 1, assigned_PersonID = NULL
WHERE requestID = i.requestid;
dbms_output.put_line('Number of row updated for requestID ' || i.requestID || ' is ' || sql%rowcount);
end loop;
commit;
end;Also i have taken the commit outside the loop. Dont perform commit inside the loop.
When you use dbms_output.put_line you can see the output only when the procedure completes the execution. So if you want to se the status during the procedure is running you may want to use DBMS_APPLICATION_INFO or create your own logging procedure and log the details. -
What do you think about using exceptions for something more than errors
if you look the java.lang.Exception description at the JDK javadoc, you can see the following text:
"The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch."
... we can�t see "error" word anywhere!!
What do you think about using exceptions for something more than errors? Can be possible use them as a way for send information to upper layers?
Thankx in regards...it seems that what you say is a functional way of achiveing that, yes
but Exceptions are generally reserverd for "Exceptional" situations ie program messing up or invalid data
it does require a fair bit of processor time to actually generate and throw an Exception.
so, all in all its "better" to use "normal" condition flow control to achive what you want.. you can always return early, break loops, call methods to pass information -
How to give color to the display of keyfigure based on condition using exception.
Dear Friends.
I am trying to color "BAD3" in exception based on condition but my problem is in exception I can have only formula variable to compare the value, How to assign a value to formula variable in BEx Query designer.
What I am trying to do is :
in Query designer :
I have PO Quantity and Delivered Quantity.
if PO Qnantity > Delivered Quantity
then Delivered Quantity field should be colored as "BAD3" in exception.
but here proble is in exception
I have alert level , operator, and value fields for Delivered Quantity keyfigure ( Under definition tab - Exception is defined on = Delivered Quantity ).
but for value field I dont have PO Quantity for that I have to supply one formula variable,
When I created a forumula and did this way
FV_PO_QUANTITY = PO_QUANTITY formula editor throws errors. I dont understand How to assign a value of key figure to formula variable and use it in EXceptions.
Please help me How I can solve my problem
I will greatly appreciate your any help.
Thanking you
Regards
NaimThank you so much for your replies,
I did following way and it helped me to solve my issues.
I created one formula and under formula I use boolean < funtion to compare the values.
like following way.
( 'PO Quantity' > 'Delivered Quantity' ) * ( FV_PO_QNT + PO_QUANTITY')
here fv_po_qnt is formula variable I supply that variable to exception and since I have the value in it.. it compares with Delievered Quantity value and colored the perticular cell.
Thanks again for your replies
Regards
Naim -
Help needed in using exceptions
can anyone please correct the code for me.
i am posting the code after doing all my homework , i tried the best of me
not able to solve the error. thanks in advance
i would prefer a clue how to solve the error even after the clue if im not able to solve i would expect the answer and explanation.
thanks in advance
import java.util.*;
public class TestExceptions
public static void main(String[] args)
String test = "no";
try
System.out.println("Start try");
doRisky(test);
System.out.println("end try");
catch ( ScaryException se )
System.out.println("Scary Exception");
finally
System.out.println("end of main");
static void doRisky(String test) throws ScaryException
System.out.println("start risky");
if("yes".equals(test))
throw new ScaryException();
System.out.println("end risky");
return;
the error i use to get is as follows
abrar-sheiks-macbook-pro:java abrarsheik$ javac TestExceptions.java
TestExceptions.java:25: cannot resolve symbol
symbol : class ScaryException
location: class TestExceptions
static void doRisky(String test) throws ScaryException
^
TestExceptions.java:15: cannot resolve symbol
symbol : class ScaryException
location: class TestExceptions
catch ( ScaryException se )
^
TestExceptions.java:31: cannot resolve symbol
symbol : class ScaryException
location: class TestExceptions
throw new ScaryException();
the erroe i use to get isAn Exception is basically a class just like any other, except that it extends java.lang.Exception.
So you either use existing ones, such as IllegalArgumentException, IllegalStateException, NullPointerException and so on, or you define your own. It seems that you wanted to define your own exception here, called ScaryException.
Defining your own exception isn't to different from writing any other class. Just write this:
public class ScaryException extends Exception {
}For the most basic part that's all you need. Later on, you might want to add some more constructors, where you can pass a message and/or a cause (which will just be passed to the super constructor). And that's usually it, most exceptions don't contain any more code than that. -
What is the best practice for using exceptions ?
hello
I would like to know when to do I have to use
1:
myMethod () throws Exception2:
myMethod () throws MyException3:
myMethod () {
try {} catch(SQLException sqlException){}
}4 :
myMethod () throws MyException {
try{} catch (ClassNotFoundException ex) {throw new MyException("error" ,ex)}
}Exception ,ClassNotFoundException and SQLException are just an example
any other exception can be in their place
thank you in advancehello
I would like to know when to do I have to use
1:
myMethod () throws Exception
Hardly ever. If you can't work out whether this is appropriate or not, it isn't, basically
2:
myMethod () throws MyException
Most of the time, if you like checked exceptions. When the exception can be recovered from
3:
myMethod () {
try {} catch(SQLException sqlException){}
Never ever ever. Don't just swallow exceptions
4 :
myMethod () throws MyException {
try{} catch (ClassNotFoundException ex) {throw new
MyException("error" ,ex)}
Opinions vary on this. If MyException is an unchecked exception, I like this. If not, you're just replacing one with the other. What for? Others will have different opinions though, and not necessarily wrong
Exception ,ClassNotFoundException and SQLException
are just an example
any other exception can be in their place
thank you in advance
Any other exceptions? Can you really treat SQLException and ClassNotFoundException the same way? One means there was a database problem, which may well be recoverable. The other? What is your app really supposed to do if it can't find a class? Rarely, this will be recoverable, perhaps. But not usually -
How to use exception for a Date Key Figure
Hello All,
I have the following requirement.
1. I have a Key Figure which is Date Type.
2. I need to color the cell to green if the it is filled with date otherwise leave it as it is.
Please suggest how to overcome it.
Thanks & Regards,
Rajibhi,
Your requirement is not clear, you have the below setup
I have the following requirement.
1. I have a Key Figure which is Date Type.
How can a KF be of date type, or is it the value of a date characteristic that you have extracted in KF using formula variable. If yes you just need to define exception for the value greater than 0.
regards,
Arvind.
Maybe you are looking for
-
Macbook Air Mid-2012 UI freeze
Hi there, I have a Mid-2012 13" Macbook Air (i7 and 8GB of RAM) with Mountain Lion and all software updates (as of 15th of November) and for the last few weeks I have been experiencing some random and very strange UI freezes. It seems to happen while
-
Ok here is the deal. I have the WRT54G Ver 6 right now. I want something that would be good for my Xbox 360, my Nintendo DS, my Nintendo Wii, a computer that is slow, another desktop that is better and then my laptop. IF you have any suggestions plea
-
How can I eliminate (watch) in videos that read "ERROR: DECODE ERROR"?
Usually when in a web site (like Fox News) & there's a video to watch I can't watch it due to the message "ERROR: DECODE ERROR". How can I eliminate this & watch the video? Thanks for your input.
-
I have tried to install flash player about a dozen times. It seems to install, says it is successful but if you check, none appears to be installed.
-
Possible to "move" Java Directory Server ?
Hi, Has anyone tried moving Java Directory server (LDAP) from one host to another ?That is not having to reinstall the Directory server when moving hosts ? I would like to know if anyone has and if any tips and tricks would be great. Thanks