Try-Catch-Throw in the same Java class - java

Is it possible to catch a method in the current class the try-catch block is running on? for example:
public static void arrayOutOfBoundsException(){
System.out.println("Array out of bounds");
}
.....
public static void doingSomething(){
try
{
if(something[i] >= something_else);
}
catch (arrayOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
If this is possible how will it be the correct way to call the catch method?
If this is not possible, could anyone point me in the right direction, of how to stop an exception from halting my program execution in Java without having to create any new classes in the package, or fixing the code that produces ArrayOutOfBoundsException error.
Thanks in Advance,
A Java Rookie

What you are wanting to do is handle an Exception.
public static void doingSomething(){
try {
if (something[i] >= something_else) { ... }
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Method Halted!, continuing doing the next thing");
}
}
That's all you need. No extra classes, no extra methods.
An Exception is a special type of class that can be "thrown" (you can throw it yourself by using the throw keyword, or Java may throw one for you if, for example, you try to access an array index that does not exist or try to perform some operation on a null). A thrown exception will "unwrap" your call stack ("escaping" from each function call) until your program finally terminates. Unless you catch it, which is exactly what the syntax above does.
So if you were writing a function a() that called a function b() that called a function c() and c() threw an exception, but the exception was not caught in b() or c(), you could still catch it in a():
void a() {
try {
b();
catch (SomeExceptionClass e) {
// Handle
}
}
That said, if it is possible to prevent an exception from being thrown in the first place, that is often a better idea. In your particular case, this would be possible since all arrays in Java know their own length:
public static void doingSomething(){
if (i >= something.length) {
System.out.println("Method Halted!, continuing doing the next thing");
} else {
if (something[i] >= something_else) { ... }
}
}

Hmm.. I think you are a little bit confused. You don't catch a method with try catch blocks. You catch Exceptions. Exceptions are more like things.
This alone (note the capital "A" of ArrayOutOfBoundsException) will prevent your program to terminate even if that Exception is thrown. You don't need to declare a "arrayOutOfBoundsException()" method.
public static void doingSomething(){
try
{
if(something[i] >= something_else);
}
catch (ArrayOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
Note the little "e"? That's the reference you can use to refer to this Exception. So, you can ask things to this Exceptions using this little local variable. For example, if you want to print where the exception happened, you can do e.printStackTrace(); .

You catch Exceptions, with a try-catch block. Not sure if you can catch methods with this.
public static void myMethod(){
try {
// check for some given condition
}
catch (conditionNotSatisfied e) {
System.out.println("Condition was not satisfied, you tried to do something which is not allowed");
}
}
The 'e' in the catch() is the reference used for referring to an Exception.
Exception refers to this when it wishes to check your given condition and return you a warning or error about the condition not getting satisfied.

I think you mean to have the arrayOutOfBoundsException method throw the exception caused... If i understand correctly:
public static void arrayOutOfBoundsExceptionMethod() throws ArrayIndexOutOfBoundsException {
\\...
\\ code that throws the exception
}
.....
public static void doingSomething(){
try
{
if(something[i] >= something_else);
arrayOutOfBoundsExceptionMethod();
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
Is that what you are asking?

I'm trying to understand what you're asking, your terminology is wrong in places :) If you try and set an index out of bounds, you'll get a built-in exception anyway, ArrayIndexOutOfBoundsException. You can catch this and use this inside the method, or throw it using a class XX throws ArrayIndexOutOfBoundsException declaration in the header of the method, so that the invoking method can catch it (its not required to catch an ArrayIndexOutOfBoundsException as it's a RuntimeException -- i.e., nothing happens if it goes uncaught, it's unchecked.
See this wiki article for more details: http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions.

It is not clear what you mean by "Is it possible to catch a method". In your case, you should write your code as :
if(i < something.length && something[i] >= something_else);
No ArrayOutOfBoundsException is needed.

Related

Why is catch block optional?

I have the following code
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
}
}
Which gives the error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type CustomException
My Question is why was it designed that the catch block is optional, when there is no way of getting around not having a catch?
From finally()'s perspective, I understand that
finally should have atleast a try block, catch is optional. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. As per the JLS
A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
Edit:
By adding a return in the finally block, compiler does not give the error WHY?!
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
return; //By adding this statement, the compiler error goes away! Please let me know why
}
}
My Question is why was it designed that the catch block is optional, when there is no way of getting around not having a catch?
Yes there is: Declare that the method throws the exception:
public static void nocatch() throws CustomException
{
try
{
throw new CustomException();
}
finally
{
}
}
try/finally without catch is to ensure that you clean up anything you need to clean up, even if you aren't handling the exception yourself. (Be sure not to allow any other exception to be thrown from within finally, or you'll hide the primary exception.)
Here's an example to play with (live copy):
private static class CustomException extends Exception {
}
public static void main (String[] args) throws java.lang.Exception
{
try
{
System.out.println("Calling nocatch(false)");
nocatch(false);
}
catch (CustomException ce) {
System.out.println("Caught CustomException for false case");
}
try
{
System.out.println("Calling nocatch(true)");
nocatch(true);
}
catch (CustomException ce) {
System.out.println("Caught CustomException for true case");
}
}
public static void nocatch(boolean foo) throws CustomException
{
try
{
if (foo) {
System.out.println("Throwing");
throw new CustomException();
}
}
finally
{
System.out.println("In finally");
}
System.out.println("Reached outside the try/finally block");
}
Output:
Calling nocatch(false)
In finally
Reached outside the try/finally block
Calling nocatch(true)
Throwing
In finally
Caught CustomException for true case
As you can see, the finally block's code runs regardless of whether an exception occurred, but the code after the try/finally doesn't.
Re your follow-up asking why adding return within the finally makes the error go away:
try
{
throw new CustomException();
}
finally
{
return; // <=== Makes the compiler happy (but don't do it!)
}
Interesting edge case! It's because the code in the finally block always runs, and so you'll always return rather than throw, hiding the exception that occurred. E.g., this is the sequence:
throw new CustomException() throws the exception, which transfers control to the finally block
Code in the finally block issues a normal return from the method
This hides the fact the exception occurred; in effect, you've "handled" the exception (without actually handling it) via the finally block. In general, this isn't a good idea; use catch to handle exceptions, or declare them on the method so calling code can handle them.

check condition using try and catch block-java

I understand the basic try-catch, where we put methods that could possibly throw exceptions in the try block. But when we need to check if something is wrong, and throw an exception, is it correct to use the code below? And the exception is caught, the program will continue to execute?
I can't tell why the try is needed here, but without it eclipse says 'syntax error'. Thanks for your help in advance!
public run (){
if (something !=true) {
try{
throw new Exception();
}catch (Exception e){
}
Yes that is correct. You have to use try since that is where the exception-throwing code is entered and where exceptions are caught (just using a catch block won't serve any purpose)
Generally speaking, exceptions are used to let the calling code handle errors in your method.
If you just want to handle the error in run, you don't need exceptions:
public void run() {
if (something != true) {
// handle it
}
}
If you want the calling code to handle the error instead, this is where you need exceptions:
public void run() throws Exception {
if (something != true) {
throw new Exception();
}
}
And where you call run, use a try/catch block:
try {
run();
} catch (Exception e) {
// handle it
}
It is also recommended that you don't throw an Exception instance, use a custom subclass instead.

How to explain whether Exception will catch RuntimeException?

This is very odd to me. RuntimeException inherits from Exception, which inherits from Throwable.
catch(Exception exc) { /* won't catch RuntimeException */
but
catch(Throwable exc) { /* will catch RuntimeException */
I know RuntimeException is special in that it's unchecked. But to my understanding that applies just to whether exceptions have to be declared, not whether they are caught. And even then, I don't know why this logic would break on catching Throwable.
This is pretty relevant to me since I have a situation where RuntimeException can be thrown in a terminal operation. I'm not sure the name for this pattern, but something like, my class EmailRoller takes an array of Callbacks. The code looks like this:
for(Callback cb : callbacks) {
try {
cb.call(item);
}
catch(Exception exc) {
logger.error("Error in callback: ", exc);
}
}
So this is a case where something like an OOME needs to fly through, because if one of these callbacks consumes all machine memory, that sure as heck is going to affect the running of the other ones. But a NullPointerException? Or an IndexOutOfBoundsException? Those will affect the callback but won't prevent the others from running.
Also, this is a bit of an enterprise design. Different programmers or teams can add callbacks to process the item, but they should be isolated from each other. This means, as the programmer responsible for insulating these callbacks from each other, I shouldn't rely on them to make sure errors don't slip through. Catching Exception should be about the right line, but it isn't because RuntimeException slips through. So my more general question is: what's a good pattern here? Just catch(Exception | RuntimeException exc), which I believe is a syntax error because of the inheritance?
The premise of the question is flawed, because catching Exception does catch RuntimeException. Demo code:
public class Test {
public static void main(String[] args) {
try {
throw new RuntimeException("Bang");
} catch (Exception e) {
System.out.println("I caught: " + e);
}
}
}
Output:
I caught: java.lang.RuntimeException: Bang
Your loop will have problems if:
callbacks is null
anything modifies callbacks while the loop is executing (if it were a collection rather than an array)
Perhaps that's what you're seeing?
catch (Exception ex) { ... }
WILL catch RuntimeException.
Whatever you put in catch block will be caught as well as the subclasses of it.
Catching Exception will catch a RuntimeException
I faced similar scenario. It was happening because classA's initilization was dependent on classB's initialization. When classB's static block faced runtime exception, classB was not initialized. Because of this, classB did not throw any exception and classA's initialization failed too.
class A{//this class will never be initialized because class B won't intialize
static{
try{
classB.someStaticMethod();
}catch(Exception e){
sysout("This comment will never be printed");
}
}
}
class B{//this class will never be initialized
static{
int i = 1/0;//throw run time exception
}
public static void someStaticMethod(){}
}
And yes...catching Exception will catch run time exceptions as well.
class Test extends Thread
{
public void run(){
try{
Thread.sleep(10000);
}catch(InterruptedException e){
System.out.println("test1");
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
Test t1=new Test1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){
System.out.println("test2");
System.out.println("Exception handled "+e);
}
}
}
Its output doesn't contain test2 , so its not handling runtime exception.
#jon skeet, #Jan Zyka

Instantiating a java if statement referencing an error

How would one write an "if statement" that checks if an error occurred in a method if so it would start a separate method that deals with the error otherwise open the next method
It is called Exception Handling.
Example:
void someMethod()
{
try
{
// Open a File
}
catch(FileNotFoundException e)
{
// Call another method
}
finally
{
// this block executes whether exception occurs or not
}
// Continue execution
}
Use a try catch statement for this. Assumign you want to crash out if the first method errors (after dealing with the exception) then the below format should work
try {
methoda();
} catch(Exception e) {
methodToDealWithError(e);
throw(e);
}
methodb();
i think try-catch block will do it for you. call your first method in try block, then call your method which deals with exceptions in catch block.
Why not just use Exceptions? Make the method throw an exception on error, catch the exception in the calling code, place error handling in the catch block??? That's what Exceptions are for!
It depends on how the method reports the error. If it returns "false" upon error you can do a trivial test:
boolean res = method();
if (!rest) {
// manage error
}
If the method however raises exception, you have to catch them with:
try {
method();
} catch (Exception e) {
// Manage exception or raise
}
Actually it depends on how method is implemented. Can you give some more info ?
methodA: The first method, it throws an exception in case en error occurs
methodB: next Method to execute, if no error occurs
methodC: error dealing method
try{
methodA();
methodB();
catch(Exception e){
methodC();
}
use Exception handling by using try catch block as
try {
Place Your Code Here...
} catch(Exception e) {
callAnotherMethodHere();
}

Java Exception Help

Can someone please explain to me the throws Exception part in the following code?
public static void main(String args[]) throws Exception {
//do something exciting...
}
Thank you in advance.
it means the function main(String[]) can throw any sub-type of Exception. in Java, all exceptions thrown by a method(except RunTimeException) must be explicitly declared.
that means every method using main(String[]) will have to take care (try,catch) Exception, or declare itself as throwing Exception as well.
Exceptions are a way Java uses to act when something unexpected happened. For example, if you want to read/write from/to a file, you have to handle IOException that will be thrown if there is a problem with the file.
A little example to explain that to you:
Let's take a method called method1() that throws an exception:
public void method1() throws MyException {
if (/* whatever you want */)
throw new MyException();
}
It can be used in two ways. The first way with method2() will simply toss the hot potatoe further:
public void method2() throws MyException {
method1();
}
The second way with method3() will take care of that exception.
public void method3() {
try {
method1();
}
catch (MyException exception) {
{
/* Whatever you want. */
}
}
For more information about exceptions, http://download.oracle.com/javase/tutorial/essential/exceptions/ should help.
EDIT
Let's say we want to return the containt of a value in this array (which is the square of the entered number): int[] squares = {0, 1, 4, 9, 16, 25}; or 0 if the number (input) is too big.
Pedestrian Programming:
if (input > squares.length)
return 0;
else
return squares[input];
Exception Guru Programming:
try {
return squares[input];
}
catch (ArrayIndexOutOfBoundException e) {
return 0;
}
The second example is cleaner, for you can also add another block (and another again) after that, so that every possible problem is fixed. For example, you can add this at the end:
catch (Exception e) { // Any other exception.
System.err.println("Unknown error");
}

Categories