I am writing a small calculator that goes through the input in token form by using streamtokenizer. However, when catching an exception I want it to either ignore all other exceptions, or move to the EOL. I can't just break as the progream isn't meant to crash, just ignore all succeeding exceptions for that input.
So either I try to set up exceptions to ignore every exception following the first, or I try to get streamtokenizer to move to EOL after catching an exception.
Either way I have no idea to get any of the two options functional.
public static void main(String[] args) throws customException {
Calculator casio = new Calculator(new Stokenizer());
while (true) {
try {
casio.statement();
}
} catch (customException error) {
System.out.println(syntaxError.getMessage());
}
}
}
Stream tokenizer docs is found at http://docs.oracle.com/javase/7/docs/api/java/io/StreamTokenizer.html
You could try something like that to go to the end of line:
public void statement() throws IOException {
int tt = StreamTokenizer.TT_EOF;
try {
while((tt = tokenizer.nextToken()) != StreamTokenizer.TT_EOF) {
// ...
}
} catch (CustomException syntaxError) {
System.out.println(syntaxError.getMessage());
gotoEOL();
}
}
private void gotoEOL() {
try {
while(tokenizer.nextToken() != StreamTokenizer.TT_EOL)
;
} catch (IOException e) {
e.printStackTrace();
}
}
Using A4Ls answer I made a little function and added it before every throw. Probably not the best solution, but it works.
private void gotoEOL() {
while (!tokenizer.isEOL()) {
tokenizer.nextToken();
// System.out.println(tokenizer.getToken());
}
Related
I have tried everything I can find on the internet, and nothing seems to fix this. I am begging for help, tell me what I am doing wrong. I am brand new to Java. Thanks!
import java.util.Scanner;
class File_Scanner {
public static void read() {
File credentials_file = new File("credentials.txt");
Scanner file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;
try {
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}
file_reader.close();
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}
This is showing the following error
Unreported exception FileNotFoundException; must be caught or declared to be thrown
I would like to recommend to surround the whole read function with a try/catch block like the following.
import java.util.Scanner;
class File_Scanner{
public static void read(){
try {
File credentials_file = new File("credentials.txt");
Scanner file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}
file_reader.close();
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}
The idea of try/catch is to avoid any error that might occur while running your program. In your case, Scanner file_reader = new Scanner(credentials_file); can throw an error if the credentials_file is not found or deleted. Hence you need to cover this around a try block which will give you an exception which can be handled to show proper response message in the catch block.
Hope that helps!
I agree with the other answers as to the problem (the Scanner can throw an exception if it can't find the file). I haven't seen what I'd consider the correct solution though.
String[] users = new String[6];
int index_counter = 0;
File credentials_file = new File("credentials.txt");
try (Scanner file_reader = new Scanner(credentials_file)) {
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
index_counter++;
}
} catch (FileNotFoundException e) {
// handle exception
} catch (NoSuchElementException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
}
The try-with-resources statement will automatically close the Scanner for you. This will work with any class that implements the AutoCloseable interface.
And in this case, it puts the statement within the scope of the try, so exceptions will be caught.
Your exception handling is questionable, so I didn't include it. But that's not really the point here. You can read more about Best Practices to Handle Exceptions in Java or How to Specify and Handle Exceptions in Java.
There is an argument that you should let the exception bubble up to the caller. This answer describes how to do that. But in this case, the caller doesn't really know how to handle a FileNotFoundException, because it doesn't know anything about the file. The file is defined in this method.
You could throw a different, more explanatory exception. Or you could handle the exception here by explaining what a credentials.txt is. Or fail over to a default. Or just log the exception, although that's questionable. If you do that, you should explain (in a comment) why that is sufficient.
I added a line to increment index_counter just because it seemed to be missing.
See also
Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?
Am I using the Java 7 try-with-resources correctly?
Java has checked exceptions. Which means that if the code within your method declares that it might possibly throw a particular exception, your method either needs to do one of the following:
Either (1) handle that exception:
public static void read() {
try {
// your method code
} catch (FileNotFoundException ex) {
// handle the exception
}
}
Or (2) declare that it might possibly throw that exception:
public static void read() throws FileNotFoundException {
// your method code
}
Just add this to your method declaration:
public static void read() throws FileNotFoundException
For ways to handle checked exceptions in java check this(Oracle Docs Java Tutorials):
You associate exception handlers with a try block by providing one or
more catch blocks directly after the try block. No code can be between
the end of the try block and the beginning of the first catch block.
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
And this:
Sometimes, it's
appropriate for code to catch exceptions that can occur within it. In
other cases, however, it's better to let a method further up the call
stack handle the exception
public void writeList() throws IOException {
P.S. Also, it has been already discussed on stackoverflow, so maybe should be marked as duplicate.
You should read the java checked exception
public static void read() {
try {
File credentials_file = new File("credentials.txt");
Scanner file_reader;
file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}
file_reader.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
System.out.println(e.getClass());
}
}
I need methodA2 also gets executed even though there is an exception by methodA1(). Here I have added only two methods as methodA1() and methodA2(). Let's say there are many methods. In that case also, the solution should be able to applicable.
class A {
String methodA1() throws ExceptionE {
// do something
}
String methodA2() throws ExceptionE {
// do something
}
}
class C extends A {
String methodC() throws ExceptionE2 {
try {
methodA1();
methodA2();
} catch (ExceptionE e) {
throw new ExceptionE2();
}
}
}
Please note that there can be many methods invoked with methodA1, methodA2. In that case having multiple try, catch, finally will look ugly.. So are there any other methods to do that?
I need to store error information in a log file. In methodA1(), methodA2() ... information in each tag is get validated. what I want is having all the error information in log file. Once exception throws it will generate log file. So I will miss validation information from other tags. So we can't go for finally approach.
You can use a loop with Java 8 lambdas:
interface RunnableE {
void run() throws Exception;
}
class Example {
public static void main(String[] args) {
List<RunnableE> methods = Arrays.asList(
() -> methodA1(),
() -> methodA2(),
() -> methodA3()
);
for (RunnableE method : methods) {
try {
method.run();
} catch (Exception e) {
// log the exception
}
}
}
private static void methodA1() throws Exception {
System.out.println("A1");
}
private static void methodA2() throws Exception {
System.out.println("A2");
}
private static void methodA3() throws Exception {
System.out.println("A3");
}
}
Please note that the interface is needed only when methods throw checked exception. If they were throwing only runtime exceptions, you could use java.lang.Runnable instead.
No other way. If each method can throw exception, but you want to continue execution of remaining methods anyway, then each method call must be in its own try-catch block.
Example:
List<Exception> exceptions = new ArrayList<>();
try {
methodA1();
} catch (Exception e) {
exceptions.add(e);
}
try {
methodA2();
} catch (Exception e) {
exceptions.add(e);
}
try {
methodA3();
} catch (Exception e) {
exceptions.add(e);
}
if (! exceptions.isEmpty()) {
if (exceptions.size() == 1)
throw exceptions.get(0);
throw new CompoundException(exceptions);
}
You will of course have to implement the CompoundException yourself.
I have a try block which handles quite a few file opening/closing/reading/writing (more than one file).
It looks like:
try {
// commands
}
catch (IOException e) {
System.err.println("Error: " + e);
}
The main problem is that e.toString() does not contain information about the filename for which the exception was thrown, if there is an error.
I could check each read/write/open/close operation separately, and then know which file the error happens with, but that seems to defeat the purpose of having the elegant try-catch structure.
Is there any other way out? I just want to be able to print the file name for which e had the error in the try block.
EDIT: Maybe I should make it clear in which scenario this issue arises. This happens when I parse command-line arguments, input/output files, etc. I pass the file names to various functions and methods that can return with an IO error. It seems reasonable to require that I would have a generic way of handling any file problem by printing the error and the filename that had that error. I understand that IOException is more broad than handling IO with files, but surely it makes sense, given that IOException is a specialized exception class, to have a method that returns the IO source for which the error occurred.
You don't - as you know, IOException doesn't have information about the File that generated the exception. It's purpose it too general. If you roll your own, you can capture relevant information and catch your own exception instead.
In the various methods that handle your input, wrap the relevant section in try/catch blocks, catch the IOException, and throw your own with the additional data.
Here is a complete program that demonstrates the basic idea.
class FooException extends Exception {
private static final long serialVersionUID = 2816777468035627105L;
private final String filename;
private final Throwable cause;
public FooException(String filename) {
this(filename, null);
}
public FooException(String filename, Throwable cause) {
this.filename = filename;
this.cause = cause;
}
#Override
public String getMessage() {
return "Error reading file";
}
#Override
public Throwable getCause() {
return cause;
}
public String getFilename() {
return filename;
}
}
public class Soj25375647 {
public static void main(String[] args) {
try {
throwsAnException();
// Do other things that might throw my exception
} catch (FooException e) {
System.err.printf("File: %s, error: %s, caused by %s%n", e.getFilename(), e, e.getCause());
}
}
public static void throwsAnException() throws FooException {
try {
int x = 2 / 0;
} catch (ArithmeticException e) {
throw new FooException("bob.file", e);
}
}
}
Output
File: bob.file, error: soj25375647.FooException: Error reading file, caused by java.lang.ArithmeticException: / by zero
See Also Exception-Handling Antipatterns.
I think I see what's happening here. You probably have something like this:
try {
for (int i = 0; i < something; i++) {
File f = getSomeFile(i);
// Operations that might throw an IOException
}
}
catch (IOException e) {
// handle
}
This is not a good idea; as you say you don't know the file that caused the error. Instead try something like this:
for (int i = 0; i < something; i++) {
File f = getSomeFile(i);
try {
// Operations that might throw an IOException
}
catch (IOException e) {
// handle
break;
}
}
This way, you still have f around when the error is thrown, but it also breaks out of the loop on an error just like the original code. Hope this helps!
Im confused how throw and catch work,I understand their are several mistakes with this ExceptionDemo. If someone could fix the mistake and clearly state why and how they corrected it without using all the Java jargon words, and use simple terms
Thank you
public class ExceptionDemo {
public static void main( String [] args ) {
try {
int number = Integer.parseInt(”123”);
if (number > 100) {
catch new ArithmeticException(”Check the number”);
}
}
catch {
System.out.println(”Cannot convert to int”);
}
finally (Exception e) {
System.out.println(”Always print”);
}
}
}
a bit tricky to tell exactly what is needed here. for starters looks like as would need to throw an exception if checking for some sort of valid value. also looks like the catch would need to have the exception handler itself not the finally.
//listing 1 slight re-work original post
public class Main {
public static void main(String[] args) throws ArithmeticException {
try {
int number = Integer.parseInt("123");
if (number > 100) {
// is this what trying to do?
//would expect typically would be used to handle
//something like div by zero, etc.
throw new ArithmeticException("Check the number");
}
}
//catch exception(s) here
catch (Exception e) {
System.out.println("Cannot convert to int:" + e.toString());
}
finally {
System.out.println("Always print");
}
}
}
//listing 2 more typical type thing maybe
public class Main {
public static void main(String[] args) {
try {
//int number = Integer.parseInt("A123"); // if un-comment throws generic exception bad input
int number = 100 / 0; //will throw an "arithmetic" exception
//
if (number > 100) {
//do something.
int x = number++;
}
}
catch (ArithmeticException arithEx){
System.out.println("An ArithmeticException Occurred:" + arithEx.toString());
}
catch (Exception e) {
System.out.println("A general exception occurred:" + e.toString());
}
finally {
//always gets executed. so is good place to clean up, close connections etc.
System.out.println("Always print");
}
}
}
In addition to hurricane's answer, you cannot catch a new exception. Instead you need to throw it.
throw new Exception();
I am new to testing with JUnit and I need a hint on testing Exceptions.
I have a simple method that throws an exception if it gets an empty input string:
public SumarniVzorec( String sumarniVzorec) throws IOException
{
if (sumarniVzorec == "")
{
IOException emptyString = new IOException("The input string is empty");
throw emptyString;
}
I want to test that the exception is actually thrown if the argument is an empty string. For that, I use following code:
#Test(expected=IOException.class)
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
}
catch (IOException e)
{ // Error
e.printStackTrace();
}
The result is that the exception is thrown, but the test fails.
What am I missing?
Thank you, Tomas
Remove try-catch block. JUnit will receive exception and handle it appropriately (consider test successful, according to your annotation). And if you supress exception, there's no way of knowing for JUnit if it was thrown.
#Test(expected=IOException.class)
public void testEmptyString() throws IOException {
new SumarniVzorec( "");
}
Also, dr jerry rightfully points out that you can't compare strings with == operator. Use equals method (or string.length == 0)
http://junit.sourceforge.net/doc/cookbook/cookbook.htm (see 'Expected Exceptions' part)
maybe sumarniVzorec.equals("") instead of sumarniVzorec == ""
how about :
#Test
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
org.junit.Assert.fail();
}
catch (IOException e)
{ // Error
e.printStackTrace();
}
Another way to do this is :
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
assertTrue(false);
}
catch (IOException e)
{
assertTrue(true);
}