Explanation
From the Java documentation:
[The try block] contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)
An exception is a special kind of object. When you write new Exception(), you are creating a new exception object. When you write throw new Exception() you are creating a new error, and then throwing it to the nearest try-catch block, aborting the rest of your code.
When you throw an exception, it gets caught by the try-catch block that it's nested in (inside of). That is, assuming the proper catch block for that exception is registered. If the code is not wrapped in a try-catch block, the program with automatically shut down as soon as an error is thrown. Use a try-catch around any code or method that can throw an error, especially because of user input (within reason).
Some exceptions have to be caught, others are optional to catch. (checked vs. unchecked).
When you add throws to a method signature, you are announcing to other methods that if they call that method, it has the potential to throw a checked exception (it is not necessary for unchecked). Notice how it's throws not throw. It's not doing an action, it's describing that it sometimes does an action.
You use this functionality when you don't want to catch the error inside that method, but want to allow the method's that call your method to catch the error themselves.
Exceptions are a way to make your program respond coherently to unexpected or invalid situations and are especially useful when user input is required, though it's also useful in other situations such as File input/output.
Examples
public CircleWithException() throws InvalidRadiusException {
this(1.0);
}
Here, the CircleWithException() has the potential to throw an InvalidRadiusException (presumably, the this(1.0) sometimes throws an InvalidRadiusException.)
The code calling this method should have:
try {
new CircleWithException(); // This calls the method above
} catch (InvalidRadiusException e) { // The object "e" is the exception object that was thrown.
// this is where you handle it if an error occurs
}
As I said before, an Exception is just a specific type of object that extends Exception
/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
private double radius;
/** Construct an exception */
public InvalidRadiusException(double radius) {
super("Invalid radius " + radius);
this.radius = radius;
}
/** Return the radius */
public double getRadius() {
return radius;
}
}
The above code defines a new type of Exception specific to your program/application. There are many predefined exceptions in the Java Standard Library, but often you need to create your own.
To throw this exception, you first create an InvalidRadiusException object and then throw it:
throw new InvalidRadiusException(1.0);
Answer from sinθ on Stack OverflowExplanation
From the Java documentation:
[The try block] contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)
An exception is a special kind of object. When you write new Exception(), you are creating a new exception object. When you write throw new Exception() you are creating a new error, and then throwing it to the nearest try-catch block, aborting the rest of your code.
When you throw an exception, it gets caught by the try-catch block that it's nested in (inside of). That is, assuming the proper catch block for that exception is registered. If the code is not wrapped in a try-catch block, the program with automatically shut down as soon as an error is thrown. Use a try-catch around any code or method that can throw an error, especially because of user input (within reason).
Some exceptions have to be caught, others are optional to catch. (checked vs. unchecked).
When you add throws to a method signature, you are announcing to other methods that if they call that method, it has the potential to throw a checked exception (it is not necessary for unchecked). Notice how it's throws not throw. It's not doing an action, it's describing that it sometimes does an action.
You use this functionality when you don't want to catch the error inside that method, but want to allow the method's that call your method to catch the error themselves.
Exceptions are a way to make your program respond coherently to unexpected or invalid situations and are especially useful when user input is required, though it's also useful in other situations such as File input/output.
Examples
public CircleWithException() throws InvalidRadiusException {
this(1.0);
}
Here, the CircleWithException() has the potential to throw an InvalidRadiusException (presumably, the this(1.0) sometimes throws an InvalidRadiusException.)
The code calling this method should have:
try {
new CircleWithException(); // This calls the method above
} catch (InvalidRadiusException e) { // The object "e" is the exception object that was thrown.
// this is where you handle it if an error occurs
}
As I said before, an Exception is just a specific type of object that extends Exception
/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
private double radius;
/** Construct an exception */
public InvalidRadiusException(double radius) {
super("Invalid radius " + radius);
this.radius = radius;
}
/** Return the radius */
public double getRadius() {
return radius;
}
}
The above code defines a new type of Exception specific to your program/application. There are many predefined exceptions in the Java Standard Library, but often you need to create your own.
To throw this exception, you first create an InvalidRadiusException object and then throw it:
throw new InvalidRadiusException(1.0);
You can declare a method to throw an exception if you can't (or it's not convinient) to handle the exception inside the method.
In your case, you are calling the method setRadius inside the constructor. If you think that is convinient to handle the exception (that is thrown by setRadius) inside the constructor, you can use a try-catch clause:
public CircleWithException(double newRadius) throws InvalidRadiusException {
try {
setRadius(newRadius);
numberOfObjects++;
} catch (InvalidRadiusException e) {
setRadius(0); // for example
}
}
The catch block contains what you want to do if an exception were thrown. In this case, I'm setting the radius to 0, but you can change this.
Remember that it depends in your classes implementation and how you want them to work. If you don't want the constructor to handle this exception, you can throw it (as you are already doing) and handle it in other methods.
Does anyone use the catch and try keywords on java?
java - What to put in a try/catch? - Software Engineering Stack Exchange
How to code a repetitive respond in a Try/Catch? - Java - Code with Mosh Forum
Java Exception Handling (Try-catch) Discussions | Java | HackerRank
Videos
Im fairly new to programming and I do not see a point of using these when I can just look at the terminal and see which line the error is in then copy and paste the error on google. Any advice on how I should use these?
In my opinion you should put everything in the block that is dependent on the part that throws the exception. So if in your second example:
try {
thisThrowsAnException();
thisDoesnt();
}
catch (Exception e) {
e.printStackTrace();
}
If thisDoesnt(); is dependent of a successful execution of thisThrowsAnException() it should be included.
Does it make sense to run it if thisThrowsAnException() fails?
It is important to note that by catching an exception you are undertaking the responsibility of recovering from it. The scope of the try block should depend on how that recovery is to be performed. For example, look at these two code snippets:
Snippet 1:
for (Object object : objects) {
try {
performTaskOnObject(object);
} catch (Exception e) {
log.error("Failed to perform task on object", e);
}
}
Snippet 2:
try {
for (Object object : objects) {
performTaskOnObject(object);
}
} catch (Exception e) {
log.error("Failed to perform task on objects", e);
}
By simply changing the scope of the try block, these two snippets present two very different recovery strategies. Snippet 1 allows the task to be attempted for the remaining Objects even after one or more failures. Snippet 2 does not allow the task to be attempted for the remaining Objects after a failure.
Your recovery strategy should be your guide to scoping your try block.