In Java exception handling:
exception包括unchecked exception、checked exception。
throw语法:
throw
throws语法:
type method_name(parameter_list) throws exception_list
{
// definition of method
}
情况1.throw unchecked exception
If we throw an unchecked exception from a method, it is not mandatory to handle the exception or declare in throws clause.
public class JavaExample
{
public static void main(String[] args)
{
method();
}
public static void method( ) {
throw new NullPointerException();
}
}
情况1.throw checked exception
if we throw a checked exception using throw statement, we MUST either handle the exception in catch block or method much explicitly declare it using throws declaration.
public class JavaExample
{
public static void main(String[] args)
{
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void method( ) throws FileNotFoundException
{
throw new FileNotFoundException();
}
}
Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.
Because the exception has already been caught at the scope in which the rethrow expression occurs, it is rethrown out to the next enclosing try block. Therefore, it cannot be handled by catch blocks at the scope in which the rethrow expression occurred. Any catch blocks for the enclosing try block have an opportunity to catch the exception.
public int cat()
{
int i=0;
try{
i=1/0;
}catch (ArithmeticException e)
{
throw e;
}
return 2;
}
public static void main(String[] args) {
Test t=new Test();
try {
int i=t.cat();
System.out.println(i);
}catch (ArithmeticException e)
{
System.out.println("m");
}
}
1.why need for Custom Exception
2.How to create a custom exception
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
参考:https://howtodoinjava.com/java/exception-handling/throw-vs-throws/