try {
// Code that may have error
} catch(ErrorName e){
// Another code
}
public class MyClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3, 4, 5, 6};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong. check again");
}
}
}
try {
// Code to try, which is throwing an Exception, e.g.
/*example*/ Thread.sleep(100)
} catch (InterruptedException e /*Or any other exception*/) {
// Handle Exception, usually:
e.printStackTrace(); // Print the StackTrace of the exception to see what cause it
} finally {
// Code executed after try / catch, used to close streams
/*example*/ in.close();
}
try{
//Code that is checked for error
} catch(Exception e){
//Code runs when error is caught
}
try {
// code
}
catch(Exception e) {
// code
}
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Unchecked:
-IndexOutOfBounds exception(while working with arrays/strings)
-NullPointerException(if I forget to instantiate the objects)
-ArithmaticException
Checked:
-IOException
-SQLException
-FileNotFountException
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
try{
// code
}
catch(exception) {
// code
}
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}