Java - Catching Exceptions Using Class Exception [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to: create a code that demonstrates how various exceptions are caught: using the code template of:
catch (Exception exception)
Thanks for all of the helpful comments.
I've revised my code:
package exception;
import java.util.Scanner;
import java.io.*;
public class Exception
{
public static void main(String args[])
{
try
{
int a[] = new int[10];
System.out.println("Access element three :" + a[11]);
// The reason this is an exception is because there is no element 11 of the array. It only has 10.
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
// This should print out whatever number was requested for a[e]
}
System.out.println("Out of the block");
// Once the exception is caught, this statement will be printed.
}
}
Output:
run:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 11
Out of the block
BUILD SUCCESSFUL (total time: 1 second)
Now my question is: Is the format done correctly? The problem requires that I use
catch (Exception exception).
I'm not sure if that's what I did - If not how can I?
Once again, thanks everyone.

The problem is with the syntax of your try-catch block.
It should be as follows:
try {
//Here goes code that might throw an exception.
}
catch(Exception e)
{
//Here goes code to handle if an exception was thrown in the try block.
}
I'm assuming your assignment hander-outer wants you to not just throw and exception with "throw new java.lang.Exception();" But instead to write some code that might throw an exception.
If you want the code to work the way you're doing it, it'll look like this:
try {
java.lang.Exception exception = new java.lang.Exception();
throw exception;
}
catch(Exception e)
{
System.out.println("I caught one!, Here's it's info: ");
e.printStackTrace();
}
However, if you want to do it the correct way, it'll look something like this:
try {
int number = 500;
int result = number / 0;
//This will throw an exception for dividing by zero.
int[] array = new int[10];
int bad = array[11];
//This will throw an ArrayIndexOutOfBoundsException
}
catch(Exception e)
{
System.out.println("I caught one! Here's some info: ")
e.printStackTrace();
}
Of course, with the code above, as soon as the first exception is thrown (by dividing by zero), the catch block will catch it and break out of the try block, so the next bad piece of code isn't ever executed.
I recommend looking here for learning what you need to know for this assignment:
https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Also here:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
And here as well:
http://docs.oracle.com/javase/tutorial/essential/exceptions/
Good Luck!
EDIT
In your catch block, you can use "System.exit(1);" Which will stop your program and have it return 1, which means that it ended its execution with an error.
However, let's say you're wanting to get a user to enter their age. You can prompt them in a try block and in the case that they enter a negative number, you could catch it with an exception and prompt again until they enter a positive number. In that case, you wouldn't want to use System.exit(1) because then your program would stop when it could keep going, all because a user gave a bad input.
That isn't a good example because you shouldn't handle such trivial things, like negative numbers, with an exception. But the idea is the same. If you want your code to continue on, you'll want to handle the error and continue. The only time to use "System.exit(1);" is if your program can't fix the error given, or if your program only did one task and that task couldn't be completed with the given input or encounters an error in doing that task.

This has included some things the other answer forgot, like scriptability (it's a good thing!)
package exception;
//import java.util.Scanner; (unused import)
import java.lang.Exception;
public class ExceptionTester {
public static void main(String[] args) {
try {
throw new Exception("Error Message Here");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
};
}
}

Related

why is the Catch exception e printing instead of doing what is in Try

I am confused why it is going to catch and print the error occurred message when I run my code since it runs and just prints the message I can't tell what the error could be
Note: this is my very first time using try and catch my professor told us to use it but haven't really learned how it works fully yet so I'm not sure if the problem is with that or if it's just with my code
public static void main (String [] args) {
try {
File file = new File("in.txt");
Scanner scanFile = new Scanner(file);
...
} catch(Exception e) {
System.out.println("Error");
}
}
Do not catch an exception unless you know what to do. It is common that you don't - most exceptions aren't 'recoverable'.
So, what do you do instead?
Simplest plan: Just tack throws Exception on your main method. public static void main(String[] args) methods should by default be declared to throws Exception, you need a pretty good reason if you want to deviate from this.
Outside of the main method, think about your method. Is the fact that it throws an exception an implementation detail (a detail that someone just reading about what the method is for would be a bit surprised by, or which could change tomorrow if you decide to rewrite the code to do the same thing but in a different way)? In that case, do not add that exception to the throws clause of your method. But if it is, just add it. Example: Any method whose very name suggests that file I/O is involved (e.g. a method called readFile), should definitely be declared to throws IOException. It'd be weird for that method not to throws that.
Occasionally you can't do that, for example because you're overriding or implementing a method from an interface or superclass that doesn't let you do this. Or, it's an implementation detail (as per 2). The usual solution then is to just catch it and rethrow it, wrapped into something else. Simplest:
} catch (IOException e) {
throw new RuntimeException("uncaught", e);
}
Note that the above is just the best default, but it's still pretty ugly. RuntimeException says very little and is not really catchable (it's too broad), but if you don't really understand what the exception means and don't want to worry about it, the above is the correct fire-and-forget. If you're using an IDE, it probably defaults to e.printStackTrace() which is really bad, fix that template immediately (print half the details, toss the rest in the garbage, then just keep on going? That's.. nuts).
Of course, if you know exactly why that exception is thrown and you know what to do about it, then.. just do that. Example of this last thing:
public int askForInt(String prompt) {
while (true) {
System.out.println(prompt + ": ");
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("-- Please enter an integral number");
}
}
}
The above code will catch the problem of the user not entering an integer and knows what to do: Re-start the loop and ask them again, until they do it right.
Just add throws Exception to your main method declaration, and toss the try/catch stuff out.
There are a couple of problems with your current code:
catch (Exception e) {
System.out.println("Error occured...");
}
Firstly, you are not printing any information about the exception that you caught. The following would be better:
catch (Exception e) {
System.out.println(e.getMessage()); // prints just the message
}
catch (Exception e) {
System.out.println(e); // prints the exception class and message
}
catch (Exception e) {
e.getStackTrace(System.out); // prints the exception stacktrace
}
Secondly, for a production quality you probably should be logging the exceptions rather than just writing diagnostics to standard output.
Finally, it is usually a bad idea to catch Exception. It is usually better to catch the exceptions that you are expecting, and allow all others to propagate.
You could also declare the main method as throws Exception and don't bother to catch it. By default, JVM will automatically produce a stacktrace for any uncaught exceptions in main. However, that is a lazy solution. And it has the disadvantage that the compiler won't tell you about checked exceptions that you haven't handled. (That is a bad thing, depending on your POV.)
now null printed out.
This is why the 2nd and 3rd alternatives are better. There are some exceptions that are created with null messages. (My guess is that it is a NullPointerException. You will need a stacktrace to work out what caused that.)
Catching Exception e is often overly broad. Java has many built-in exceptions, and a generic Exception will catch all of them. Alternatively, consider using multiple catch blocks to dictate how your program should handle the individual exceptions you expect to encounter.
catch (ArithmeticException e) {
// How your program should handle an ArithmeticException
} catch (NullPointerException e) {
// How your program should handle a NullPointerException
}

Exception handling without try block [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I think this is correct... When an exception occurs an object of the exception class is thrown and if we dont use a try or catch block, then the object goes to the JVM.
My question is why is the try block necessary, why wouldn't a catch block be good enough since the exception object is not created in the try block? I know that java requires you to use a try block to test the code in which the exception might occur, but was wondering if the exception object is created either way, then why couldn't a catch block been sufficient enough. This question is different from other exception handling questions in that it doesn't appear anyone has asked about needing to have the try block specifically.
The try { } portion indicates the section of code the catch { } block is protecting.
void test() {
do_something(); // Not covered
try {
something_fixable(); // Covered
} catch (InvalidStateException ex) {
do_recovery_for_fixable_thing();
}
}
Without the try { } block, the catch { } block might try to catch an exception other than the one it can handle.
Even if the exception thrown by do_something() is the same kind of exception, an InvalidStateException, the recovery code won't handle it; it isn't supposed to.
Suppose you had the following
doSomething(); // throws Exception1
doNothing(); // throws Exception2 which extends Exception1
catch(Exception 1 ex){ // handle exception }
To what does the catch block apply? Will it act only if an exception is thrown in doNothing()? Or will it also apply to the call to doSomething(). Or perhaps it will only apply to doSomething() and not doNothing(), which throws Exception2.
There is precedent for the omission of brackets. For example consider the next 2 groups of code.
int i;
for( i = 0 ; i < 10 ; i++)
System.out.println("hello World" + i);
and
int i;
for( i = 0 ; i < 10 ; i++)
{
System.out.println("hello World" + i);
}
Here the for statement is understood to act either on the next bracketed block or next single line of code.
So I suppose it might have been possible to have catch statements work on the previous statement or on the previous block. But that is just syntactic sugar, right? There is no functionality that you lose by requiring a try block.

Try-catch-finally order of execution appears to be random [duplicate]

This question already has an answer here:
Why does the execution order between the printStackTrace() and the other methods appear to be nondeterministic?
(1 answer)
Closed 7 years ago.
I am trying to understand how the try-catch-finally execution flow works. There are a couple of solutions from Stack Overflow users regarding their execution flow.
One such example is:
try {
// ... some code: A
}
catch(...) {
// ... exception code: B
}
finally {
// finally code: C
}
Code A is going to be executed. If all goes well (i.e. no exceptions get thrown while A is executing), it is going to go to finally, so code C is going to be executed. If an exception is thrown while A is executed, then it will go to B and then finally to C.
However, I got different execution flows when I tried it:
try {
int a=4;
int b=0;
int c=a/b;
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally {
System.out.println("common");
}
I am getting two different outputs:
First output:
java.lang.ArithmeticException: / by zero
at substrings.main(substrings.java:15)
lication.AppMain.main(AppMain.java:140)
common
However, when I ran the same program for the second time:
Second output:
common
java.lang.ArithmeticException: / by zero
at substrings.main(substrings.java:15)
What should I conclude from this? Is it going to be random?
printStackTrace() outputs to standard error. System.out.println("common") outputs to standard output. Both of them are routed to the same console, but the order in which they appear on that console is not necessarily the order in which they were executed.
If you write to the same stream in both catch block and finally block (for example, try System.err.println("common")), you'll see that the catch block is always executed before the finally block when an exception is caught.
Exception's printstacktrace() method source code(defined in Throwable class)
public void printStackTrace() {
printStackTrace(System.err);
}
The formatting of output occurs because your are using standard output stream through System.out.printlnand exception occurs System.err stream
Try having a variable which will check exceptions and print in same error console if exception occurs :-
boolean isException = false;
try {
int a=4;
int b=0;
int c=a/b;
}
catch (Exception ex)
{
isException = true
ex.printStackTrace();
}
finally {
if(isException){
System.err.println("common");
}else{
System.out.println("common");
}
}

Why won't main method catch the uncaught exception from catch block

I came up with this example while studying mock exams for OCPJP certification,
(from http://www.certpal.com version 1.6 exam part 3, Flow Control, Question number 8)
public class Oak
{
public static void main(String args[])
{
try
{
Integer i =null;
i.toString();
}
catch (Exception e)
{
try
{
System.out.println("One ");
Integer i =null;
i.toString();
}
catch (Exception x)
{
System.out.println("Two ");
Integer i =null;
i.toString();
}
finally
{
System.out.println("Three ");
Integer i =null;
i.toString();
}
}
finally
{
System.out.println("Four ");
}
}
}
I am fully aware that finally blocks always execute unless there is a System.exit(), so I traced the program and decided that it will have an output like this
One Two Exception in thread "main" java.lang.NullPointerException Three Exception in thread "main" java.lang.NullPointerException Four
However, it turns out the correct output is (according to the site and Eclipse debugging)
One Two Three Four Exception in thread "main" java.lang.NullPointerException
What I'm not understanding is, where did the exception which occurs in catch block with "Two" go?
There is no catch block underneath that, shouldn't it be thrown by the main thread too? Because it's not catched?
That exception is effectively lost - if a finally block throws an exception, any exception which was in the course of propagating becomes irrelevant, and the result of the finally block is the new exception.
Likewise if you return in a finally block, then that overall try/catch/finally will never throw an exception.
See section 14.20.2 of the Java Language Specification for details. In particular, various bits like this:
If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

Learning Try-Catch

I'm a Java beginner so please bear with me
static int load = 100;
static int greet;
public void loadDeduct(int cLoad, int c){
int balance;
balance = cLoad - 7;
System.out.println("Your balance: " + balance);
}
public void loadDeduct(int tLoad){
int balance;
balance = tLoad - 1;
System.out.println("Your balance is: " + balance);
}
public static void main (String [] args){
int choice;
Scanner scan = new Scanner(System.in);
System.out.println("I'm a cellphone, what do you want to do?");
System.out.println("Press 1 to send SMS / Press 2 to Call");
choice = scan.nextInt();
CellphoneLoad N95 = new CellphoneLoad();
if (choice == 1){
N95.loadDeduct(load);
}else if (choice == 2){
N95.loadDeduct(load, greet);
}else{
System.out.println("Invalid Option!!!");
}
How do I implement the exception handling with this program?
I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. It was just an exercise we were asked to do. I want to replace the if else statements with a try-catch blocks... is that possible?
One important principle to consider with exceptions in Java is that there are two types:
1. Runtime
2. Typed/explicit (for lack of a better word)
Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error.
Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them.
In the case of the code above, there isn't really a place that feels like it should use exception handling.
And as Patrick pointed out, you don't generally want to use exceptions for flow control.
It is not ideal to use Exceptions for flow control. From your code it is not clear what Exceptions might be thrown. Maybe you can elaborate a bit more.
The Scanner.nextInt() method can throw a few exceptions. The linked page of the API Specifications lists out the three exceptions which can be thrown.
For example, if a non-integer value is entered, such as "one" instead of 1, an InputMismatchException can be thrown.
In general, a try-catch is used to catch exceptions, as illustrated in the following code:
try
{
Integer.parseInt("one"); // Statement that can cause an exception.
}
catch (NumberFormatException e) // Specify which exception to catch.
{
// Code to handle the NumberFormatException.
}
More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials. In particular, the Catching and Handling Exceptions section may be useful.
Adding exceptions in this piece of code does not add much value.
What I can think of is something like this:
public static void main (String [] args){
.....
try{
handleUserChoice(choice);//new method
}
catch(InvalidChoiceException e){
System.out.println("Invalid Option!!!");
}
}
The only part of your code that might possibly throw an exception is the call to:
scan.nextInt();
According to the JavaDocs, this can throw the following possible exceptions:
InputMismatchException (if the next
token does not match the Integer
regular expression, or is out of
range)
NoSuchElementException (if
input is exhausted)
IllegalStateException (if this
scanner is closed)
So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so:
try {
choice = scan.nextInt();
}
catch (InputMismatchException e) {
System.out.println(e.getMessage());
}
catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature.
You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime).
In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement:
switch (choice) {
case 1: N95.loadDeduct(load);
break;
case 2: N95.loadDeduct(load, greet);
break;
default: System.out.println("Invalid Option!!!");
}
I don't see any reason to use exceptions instead of the if-else block. you could try using a switch statement, it'd look better.
you should use exceptions to handle errors that might occur inside the methods loadDeduct. then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong.
It's really pretty simple. First identify where you want an exceptioon. There can be exceptinos thrown by library code or you can throw your own. Then use a try .. catch to handle it. Here's a simple "hello, world" ish example:
public class TryTry {
public void doIt() throws Exception {
System.err.println("In the doIt method.");
throw new Exception("Hello there!");
}
public static void main(String[] argv){
TryTry t = new TryTry();
// here we'll catch it.
try {
System.err.println("About to call doIt().");
t.doIt();
} catch (Exception e) { // e now has your exception object
System.err.println("In the exception handler.");
System.err.println("Exception says: "+ e);
}
}
}
The effect of throw is to construct that exception object and send it up the stack until it's caught. To catch it, you surround the code that might throw it with tr { ... }, and handle the exception with catch.
Here's the results:
javac TryTry.java && java TryTry
About to call doIt().
In the doIt method.
In the exception handler.
Exception says: java.lang.Exception: Hello there!

Categories