How to throw exception for statment? - java

HI !
I want to throw exception for the line
BarcodeNo=Long.parseLong(jTextField1.getText())
I done this in a way
BarcodeNo=Long.parseLong(jTextField1.getText()) throw new NumberFormatException("Enter Numbers Only ");
But this way compiler throws error stating ";" required
So anyone can tell me how to do this ?
Thanks

That will already thrown an exception if the text isn't in the right format. If you want to change the exception message, you'd have to catch the exception and throw a new one:
try {
BarcodeNo = Long.parseLong(jTextField1.getText());
} catch (NumberFormatException e) {
throw new NumberFormatException("Enter Numbers Only");
}
I wouldn't suggest that you try to use exception message as user-visible messages though - they're more reasonable for logging than for showing an end user.

yes you should put
try
{
BarcodeNo=Long.parseLong(jTextField1.getText());
}
catch(Exception e)
{
throw new NumberFormatException("Enter Numbers Only ");
}

Related

Can I throw exception again when I catch it?

try{
WebElement naimi_logo = firefox.findElement(By.xpath("//a[#href=\"/astana/\"]/img") ) ;
naimi_logo.click();
}catch( IllegalStateException e){
throw new IllegalStateException("this image is not clickable!") ;
}
catch(NoSuchElementException e){
throw new NoSuchElementException("logo is not found!!") ;
}
Should I really throw exception in my catch block? Or is it better to just print what happened to console?
Does the order of the catches matter?
It looks like your intent is to add more information when an exception occurs. In that case what you are doing is fine. However you will lose complete stack trace for the underlying exception.
You can use:
java.lang.RuntimeException.RuntimeException(String, Throwable)
If you don't want to lose the stack trace of original exception.
Can I throw exception again when I catch it?
To just rethrow the exception you do
throw e;
On the other hand this is equivalent of not catching the exception at all and let it propagate.
Perhaps you want to give the exception a better message, but keep the exception class. You would then typically do:
}catch( IllegalStateException e){
throw new IllegalStateException("this image is not clickable!", e);
}
catch(NoSuchElementException e){
throw new NoSuchElementException("logo is not found!!", e);
}
Should I really throw exception in my catch block?
This depends on what your method is intended to do. Your options are basically
Catch and handle the exception gracefully. Your method can complete normally even in case of an "internal" exception.
Catch the exception and wrap it in another exception more suitable for your level of abstraction.
Let the exception propagate.

Throwing exception error

My program is not compiling and showing me this error:
System.out.println("Error: "+ e.getMessage());
Scanner scanner = new Scanner(System.in);
try {
int num = scanner.nextInt();
if (num != 0) {
throw new Exception("Not zero");
}
System.out.println("I'm happy with the input.");
} catch (InputMismatchException e) //InputMismatchException is never thrown in body of corresponding try statement
{
System.out.println("Invalid Entry");
} catch (Exception e) {
System.out.println("Error: "+ e.getMessage());
}
The error message is quite clear:
InputMismatchException is never thrown in body of corresponding try statement
You're trying to catch an exception which is guaranteed not to be thrown from the try block. This is useless, and even invalid. Remove the catch (InputMismatchException e) block.
Actually, the try block can throw a java.util.InputMismatchException. So I guess that you're in fact catching an InputMismatchException of another package. Check your imports, and make sure you import java.util.InputMismatchException and not some other com.foo.bar.InputMismatchException.
EDIT:
the error message confirms what I thought. You're catching javaapplication9.InputMismatchException, instead of java.util.InputMismatchException. I'm not sure why you defined your own InputMismatchException.

How do I display an exception?

I am checking if number the user entered is Zeckendorf and I want to display an exception if it is not, how do i do that? Also how do I convert the Zeckondorf to its decimal equivalent?
import java.util.Scanner;
public class IZeckendorfNumberConvertor {
static String number;
int zeckonderEquivalent;
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
convertToZeckonderNumber();
isTrueZeckonderNumber();
}
private static boolean isTrueZeckonderNumber() {
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100"))
{
return true; }
else if (number.equals("010011") || number.equals("010100"))
{
return false; }
return false;
}
private static void convertToZeckonderNumber() {
}}
I advise you not to display an exception (i.e. trace and such) as it is very user Unfriendly.
You can use the throw syntax to throw a proper exception :
throw new Exception("Given number is not a Zeckendorf number");
but be sure to catch it and display a nice and clean message :
try {
// Your input code goes here
} catch (Exception e) {
System.out.println(e.getMessage());
}
Another easier option will be to just check the return value of the method and print the results accordingly.
I will recommend to use the latter solution as exceptions are used when something bad and unexpected happens in your program and you want to handle it gracefully. In your case the behavior is expected (i.e. user giving a wrong number) so checking the return value will be much clean and easier.
Use try catch block for catch an exception
try {
} catch (Exception e) {
e.printStackTrace();
}
Also use throw for throw a new exception
Assuming to really do want to display the exception, and not a more user friendly message, the first step is probably to get the exception as a string. Then you can do what you like with that string (echo to console, place in a javax.swing.JTextArea, email it, etc).
If you just want the message from the exception, then getMessage() will do:
try { ... }
catch(FooException e) {
String msg = e.getMessage();
}
However, if you want the whole exception, stack trace and all, you'll want something like this:
public static String stackTrace(Exception e) {
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
return w.toString();
}
// ...
try { ... }
catch(FooException e) {
String st = stackTrace(e);
}
If you just want to echo the full stack trace to the console, there is the printStackTrace(), no-arg method:
try { ... }
catch(FooException e) {
e.printStackTrace();
}
If you want to take more control of the presentation of the stack trace you can get the details with:
try { ... }
catch(FooException e) {
StackTraceElement[] stes = e.getStackTrace();
// Do something pretty with 'stes' here...
}
You can just print a error message to the user saying that the input is wrong using a simple if.
if(yourCondition){
// Happy scenario
// Go shead
}else{
// Error Scenario
System.out.println("Error. Invalid Input.");
// If you persist to throw an exception, then you can do something like this
// throw new Exception("Exception Explanation"); // I've commented this, but you can uncomment it if needed
// But the advice is to display an error message, than throw a exception.
}
And regarding the conversion, you can convert binary to decimal like this
int i = Integer.parseInt(binaryString, 2); // 2 indicates the radix here, since you want to convert from binary.
With this code snippet you can convert the String into an integer :
int numberAsInt;
try {
numberAsInt = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will throw an Exception
}
If you want to create your own Exception class, you can do it like shown here or just throw a RuntimeException with
throw new RuntimeException("Your Message");
My opinion, you can try some thing like following
public static void main(String[] args) {
if(!isTrueZeckonderNumber()){
// your message should goes here
System.out.println("Your message");
}
}
If you really want to throws an exception do following
private static boolean isTrueZeckonderNumber() throws Exception{
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100")) {
return true;
} else{
throw new Exception("your message");
}
}
What do you mean you want to display an exception?
I would suggest just giving the user feedback instead, as exceptions are used more commonly for EXCEPTIONAL actions that are not supposed to happen.
However if you do want to, you can print a message explaining what happened.
try {
} catch (Exception e) {
System.out.println(e.getMessage());
}

Getting error number of an exception object

I have a program developed and it has a single entry point. A Try catch block is surrounding it.
try {
Runner runner = new Runner();
// Adhoc code
UIManager.setLookAndFeel(new NimbusLookAndFeel());
runner.setupVariables();
runner.setLookAndFeel();
runner.startSessionFactory();
runner.setupApplicationVariables();
runner.setupDirectories();
// This will be used to test out frames in development mode
if (Runner.isProduction == true) {
execute();
} else {
test();
}
} catch (Exception e) {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
Logger.getRootLogger().error(e);
e.printStackTrace();
}
But suppose a null pointer exception is thrown, the message box is empty since the Exception doesn't contain a message. For this I added a logic-
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at ");
}else{
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
This works all fine but I also want the line number to be displayed. How can I get it done. How can I get the line number of the exception?
Among the answer to this question, you can use this snippet:
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
Althought is recommended to use a logging library such as log4j.
The metadata for the exception is stored in StackTraceElement class, which you can get from your exception by calling getStackTrace().
Example of using it is:
if (e instanceof NullPointerException) {
NullPointerException n = (NullPointerException) e;
StackTraceElement stackTrace = n.getStackTrace()[0];
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at " + stactTrace.getLineNumber());
}
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at line" + e.getStackTrace()[0].getLineNumber());
} else {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
Wow I was ninja'd by those above...
EDIT: Forgot to indent

Question about how to exit program with exception

Assume that I want to exit a console program if the user entered the char f, and in any time of the program.
The user is supposed to enter some info but I want for each step he entering the input to be able to stop all the operation if he entered "f"?
How can I do that?
Should it be something like:
try
{
if (userchoice.equals("F"))
{
throw new exception e;
}
}
catch (exception e)
{
System.exit(1);
}
Thanks
You can throw the exception, unless it is caught it will cause the current thread to die.
if ("f".equalsCaseIgnore(userchoice))
throw new IllegalArgumentException("Option "+userchoice+" not allowed.");
Here's the correct syntax:
try {
if (userchoice.equals("F")) {
throw new Exception();
}
} catch (Exception e){
System.exit(1);
}
Hint:
Scanner class
System.exit();
The input of the char "f" is expected behavior and so throwing an exception may be wrong way.
Encapsulate your input in a method which is responsible to handle the input and decided behavior.
Just call system.exit() here if the user entered "f" or call an exit method that does the work.
Do the following.
Read the input from the command line using classes like BufferedReader or Scanner.
Check for the character "f" from the i/p'ed string.
Throw your exception using throw new MyException();
Catch the exception in the catch block and terminate it with System.exit(1);
If you require "f" or "F", use equalsIgnoreCase() function.
Try something like this,
try{
if (userchoice.equals("F")) {
throw new MyException;
}
}
catch (MyException e) {
System.out.println("MyException caught because i/p character was F" + e);
System.exit(1);
}

Categories

Resources