自定义异常处理

package com;

import java.util.Scanner;

public class ScoreException extends Exception{
    public ScoreException(){
    }
    public ScoreException(String message){
        super(message);
    }
}

package com;

public class Teacher {
    public void check(int score) throws ScoreException{
        if(score < 0 || score >100){
            throw new ScoreException("你给的分数有误!");
        }else{
            System.out.println("输入正确");
        }
    }
}

package com;
import java.util.Scanner;
public class TeacherTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int s = sc.nextInt();
        Teacher t = new Teacher();
        t.check(s);//因为定义的是编译时异常,所以必须使用以下异常处理语句,
                    //若定义的异常类继承自RuntimeException即运行时异常,则可以不用下面语句。
//        try {
//            t.check(s);
//        } catch (ScoreException e) {
//            e.printStackTrace();
//        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 是一个基于 Spring 的安全框架,其支持多种认证方式、授权方式以及自定义安全过滤器等。在使用 Spring Security 进行开发时,自定义异常处理是非常重要的一部分。下面是 Spring Security 自定义异常处理的步骤: 1. 实现 AuthenticationEntryPoint 接口,该接口用于处理未认证用户的请求。通过实现该接口,可以自定义未认证用户的返回结果,例如返回自定义的 JSON 格式数据或者跳转到自定义的登录页面。 2. 实现 AccessDeniedHandler 接口,该接口用于处理已认证用户但没有权限访问资源的请求。同样可以通过实现该接口,自定义返回结果。 实现以上两个接口之后,需要在 Spring Security 配置中进行配置,将自定义实现的类添加到配置中即可生效。下面是一个示例配置: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticationEntryPoint myAuthenticationEntryPoint; @Autowired private MyAccessDeniedHandler myAccessDeniedHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.exceptionHandling() .authenticationEntryPoint(myAuthenticationEntryPoint) .accessDeniedHandler(myAccessDeniedHandler) .and() .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() .and() .formLogin().loginPage("/login").permitAll() .and() .logout().permitAll(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值