Is it a sin if one is attacked (e.g. by robbers and murderers) and if one unintentionally kills ones attacker?
Answer: The action described in this question is called self-defence.
The legitimate defence of persons and societies is not an exception to the prohibition against the murder of the innocent that constitutes intentional killing. The act of self-defence can have a double effect: the preservation of ones own life; and the killing of the aggressor... The one is intended, the other not. (Thomas A., s. th. 2-2,64,7). [CCC 2263]
Love toward oneself remains a fundamental principle of morality. Therefore it is legitimate to insist on respect for one’s own right to life. Someone who defends his life is not guilty of murder even if he is forced to deal his aggressor a lethal blow:
If a man in self-defence uses more than necessary violence, it will be unlawful: whereas if he repels force with moderation, his defence will be lawful.... Nor is it necessary for salvation that a man omit the act of moderate self-defence to avoid killing the other man, since one is bound to take more care of ones own life than of another’s. (Thomas A., s. th. 2-2,64.7) [CCC 2264]
Legitimate defence can be not only a right but a grave duty for someone responsible for another's life. Preserving the common good requires rendering the unjust aggressor unable to inflict harm. To this end, those holding legitimate authority have the right to repel by armed force aggressors against the civil community entrusted to their charge. [CCC 2265]
The States effort to contain the spread of behaviour injurious to human rights and the fundamental rules of civil coexistence corresponds to the requirement of watching over the common good. Legitimate public authority has the right and duty to inflict penalties commensurate with the gravity of the crime. The primary scope of the penalty is to redress the disorder caused by the offence. When his punishment is voluntarily accepted by the offender, it takes on the value of expiation. Moreover, punishment, in addition to preserving public order and the safety of persons, has a medicinal scope: as far as possible it should contribute to the correction of the offender. [CCC 2266)
The traditional teaching of the Church does not exclude, presupposing full ascertainment of the identity and responsibility of the offender, recourse to the death penalty, when this is the only practicable way to defend the lives of human beings effectively against the aggressor. [CCC 2267]